Question

In: Computer Science

Python using sqllite3 package In this exercise, your task is to inspect the given database, which...

Python using sqllite3 package

In this exercise, your task is to inspect the given database, which is called 'chinook.db', as you can see from the testing code below in the example. We first would like to know how the logical schema of the database looks like, in order to work with it later in terms of reading from and writing to the database. Please also note that a software tool like "DB Browser for SQLite" can be used to inspect and modify an SQLite database file like 'chinook.db'.

To solve this exercise you have to write a function get_table_information_from_database(database_filename), which returns a dictionary that has all the available table names as its keys, and a list of the column names for the respective table as its values. The column names are the second entries in the record returned from the "PRAGMA table_info" SQL statement given below.

Regarding the structure of this code, you have to make sure that the Python sqlite3 package is first imported. Using the connect method from this package, a database connection can be opened. This connection uses the concept of a cursor object to send SQL statements to the database in the form of strings. In case the SQL string represents a query, the cursor.execute method returns a result containing the result of this query. This result is a list and can be inspected here in this question for the logical schema information.

The necessary SQL statements you need are:

  • "SELECT name FROM sqlite_master WHERE type='table'"
  • and for each table, identified by a string 'table_name': "PRAGMA table_info('table_name')"

Attention: Please ignore table names that start with the substring "sqlite" from the query result, since these are internal tables, which in general should not be used by an application!

Don't forget to close the database connection after you are finished accessing the database!

Please have a look at the examples in the lecture slides for lecture 15 to see examples of SQLite being used. Additionally, you may want to look up more information on the web page for Python's SQLite API here. SQL statements are simply strings, which can be concatenated using string literals and string variables.

Note: As always, it is a good idea to work on this example using your favourite IDE first (download the database file), before you enter it into coderunner. This way you can more easily debug your code!

For example:

Test Result
database_filename = 'chinook.db'
metadata_dictionary = get_table_information_from_database(database_filename)

for table in sorted(metadata_dictionary.keys()):
   print("{}: {}".format(table, metadata_dictionary[table]))
albums: ['AlbumId', 'Title', 'ArtistId']
artists: ['ArtistId', 'Name']
customers: ['CustomerId', 'FirstName', 'LastName', 'Company', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email', 'SupportRepId']
employees: ['EmployeeId', 'LastName', 'FirstName', 'Title', 'ReportsTo', 'BirthDate', 'HireDate', 'Address', 'City', 'State', 'Country', 'PostalCode', 'Phone', 'Fax', 'Email']
genres: ['GenreId', 'Name']
invoice_items: ['InvoiceLineId', 'InvoiceId', 'TrackId', 'UnitPrice', 'Quantity']
invoices: ['InvoiceId', 'CustomerId', 'InvoiceDate', 'BillingAddress', 'BillingCity', 'BillingState', 'BillingCountry', 'BillingPostalCode', 'Total']
media_types: ['MediaTypeId', 'Name']
playlist_track: ['PlaylistId', 'TrackId']
playlists: ['PlaylistId', 'Name']
tracks: ['TrackId', 'Name', 'AlbumId', 'MediaTypeId', 'GenreId', 'Composer', 'Milliseconds', 'Bytes', 'UnitPrice']

given start code

import sqlite3

def get_table_information_from_database(database_filename):
pass

Solutions

Expert Solution

I have writtend relevant comments for each line in code:

I am providing the outputs for my own database because I dont have the chinook.db file

So you can check the output format for any database doesn't change:

You can change your database name while passing it to the function get_table_information_from_database

import sqlite3

def get_table_information_from_database(database_filename):
    """Given The Database Name it will Return Database 
       Tables and There Keys in Dictionary Format Keys as
       Table Names and List of Column Names as it Values.
    """
    metadata_dictionary = {} # Creating a Empty Dictionary 
    conn = sqlite3.connect(database_filename) # Connect to Sqlite Database for a given database file name
    print("Opened database successfully") # Printing for Database Successuflly opened
    cur = conn.cursor() # Creating a cursor object using the cursor() method
    cur.execute("SELECT name FROM sqlite_master WHERE type='table'") # Executing query using cursor getting all tables present in the database
    table_names = [] # Empty list for storing all table names
    for name in cur.fetchall(): # Looping over the results which are fetched from executing the above query
        if not name[0].startswith("sqlite"): # only collecting tables which doesn't startswith "sqlite"
            table_names.append(name[0])
    for table_name in table_names: # Looping over each table name and querying on that
        cur.execute("PRAGMA table_info({})".format(table_name)) # query for each table information with same cursor
        # collecting only the table column names into a single list from the fetched results and placing into the dictionary
        metadata_dictionary[table_name] = [info[1] for info in cur.fetchall()] 
    conn.close() # closing connection to database
    return metadata_dictionary # return the created dictionary


database_filename = 'VSAPT.db' # change the database name as per your requirements
metadata_dictionary = get_table_information_from_database(database_filename) # calling the function
for table in sorted(metadata_dictionary.keys()):
    print("{}: {}".format(table, metadata_dictionary[table]))

Code screenshort with output

You can see the output is Table_name and the Column Names as list for that key

If any doubt further please drop a comment


Related Solutions

SQL DATABASE Task 2 [10.5 marks] using the AdditionCollege database For task 2, we have provided...
SQL DATABASE Task 2 [10.5 marks] using the AdditionCollege database For task 2, we have provided you with the creation script for the AdditionCollege database. Run this script in MySQL Workbench to create the database. You should execute your query solutions to extract the necessary information. The script is based on the following schematic: Unit (Unit_code, Staff_id, [UnitName]) Staff (Staff_id, StaffName, Position, Gender) Taught_by (Unit_code, Staff_id, weekday) Student (Student_id, Student_name, Address, Gender) TuteGroup (TuteGroup_code, Unit_code, DayHrCode, Room_Nr) TuteGroup_List (TuteGroup_code, Student_id)...
Your task in this exercise is to write a function called get_playlist_tracks(database_filename, which_playlist), which formulates a...
Your task in this exercise is to write a function called get_playlist_tracks(database_filename, which_playlist), which formulates a SELECT statement that returns track name, album title, genre name, artist name and track composer for all tracks in the database which are associated with a given playlist. This statement requires several nested INNER JOINs to pull together data from the "tracks", "albums", "genres", "artists", and "playlists" table. The default ordering of tracks should be used. The result of the function is a list...
Database exercise: inpatient cases Create database using name RUMKIT Create tables below in that database patient(idPatient,...
Database exercise: inpatient cases Create database using name RUMKIT Create tables below in that database patient(idPatient, fullName, biologicalMother, birthdate, address) doctor(idDr, fullName, specialization, consulRates) inpatient(idPatient, entryTime, outTime, idDr, idRoom). Please make entryTime as column that is going to be filled automatically when care record is being add room(idRoom, roomName, cost) fill the data above to each table Create sql query and relational algebra expressions for the query Please give me detailed answer so I could learn from it. Thank you...
Given is a Python program that connects to a sqlite database and has one table called...
Given is a Python program that connects to a sqlite database and has one table called writers with two columnns: name - the name of a writer num - the number of works the writer has written The writers table originally has the following data: name, num Jane Austen,6 Charles Dickens,20 Ernest Hemingway,9 Jack Kerouac,22 F. Scott Fitzgerald,8 Mary Shelley,7 Charlotte Bronte,5 Mark Twain,11 Agatha Christie,73 Ian Flemming,14 J.K. Rowling,14 Stephen King,54 Oscar Wilde,1 Update the Python program to ask...
Using Python, write a segment of code to populate the table "employee" of the database "EmployeeDB”...
Using Python, write a segment of code to populate the table "employee" of the database "EmployeeDB” with the data below. Import your choice of DB connector (import MySQLdb/sqlite3…) Create the“employee” table with schema = [name, address, age] Insert this employee: John Doe, 7001 E Williams Field, 32
Using Java please You are given an array of integers arr. Your task is to count...
Using Java please You are given an array of integers arr. Your task is to count the number of contiguous subarrays, such that each element of the subarray appears at least twice. E.g For arr = [0, 0, 0], the output should be duplicatesOnSegment(arr) = 3.
Your task is to determine the WACC for a given firm using what you know about...
Your task is to determine the WACC for a given firm using what you know about WACC as well as data you can find through research. Your deliverable is a brief report in which you state your determination of WACC, describe and justify how you determined the number, and provide relevant information as to the sources of your data. Select a publicly traded company that has debt or bonds and common stock to calculate the current WACC. One good source...
PYTHON Exercise: Accelerate Method ------------------------- ### Description In this exercise, you will add to your `Car`...
PYTHON Exercise: Accelerate Method ------------------------- ### Description In this exercise, you will add to your `Car` class a method to accelerate the speed of an instance. ### Class Name `Car` ### Method `accelerate()` ### Parameters * `self` : the `Car` object to use * `delta_speed` : a number, the desired value to add to the speed data member. ### Action Adds `delta_speed` to the speed of the object. If the new speed is too fast, then set the speed to...
Hi, I would be grateful for some helot with this Python problem. Your task is to...
Hi, I would be grateful for some helot with this Python problem. Your task is to implement the simple elevator in Python using classes. The default strategy is the simple "start at the bottom, go to the top, then go to the bottom". Can you write a better strategy, one that is more efficient? Description / Specification Create three classes: Building, Elevator, and Customer. Equip the building with an elevator. Ask user to customize the number of floors and the...
CODE IN PYTHON: Your task is to write a simple program that would allow a user...
CODE IN PYTHON: Your task is to write a simple program that would allow a user to compute the cost of a road trip with a car. User will enter the total distance to be traveled in miles along with the miles per gallon (MPG) information of the car he drives and the per gallon cost of gas. Using these 3 pieces of information you can compute the gas cost of the trip. User will also enter the number of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT