Question: I want to code a context manager class called [PersonDB] that will provide read access to the database created with this code: ------------------------------------------------------------------------------------ import random

I want to code a context manager class called [PersonDB] that will provide read access to the database created with this code:

------------------------------------------------------------------------------------

import random import sqlite3 from sqlite3 import Error

def generate_people(count): first_names= [] last_names= [] with open('LastNames.txt', 'r') as filehandle: while True: line = filehandle.readline() if not line: break line = line.rstrip() last_names.append(line) with open('FirstNames.txt', 'r') as filehandle: while True: line = filehandle.readline() if not line: break line = line.rstrip() first_names.append(line) random_names = []

for id in range(count): first_name_index = random.randint(0, len(first_names)-1) last_name_index = random.randint(0, len(last_names)-1) random_names.append((id, first_names[first_name_index], last_names[last_name_index])) return random_names

if __name__ == "__main__": people = generate_people(5)

people_db_file = "sqlite.db" # The name of the database file to use max_people = 500 # Number of records to create

def create_people_database(db_file, count): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) with conn: sql_create_people_table = """ CREATE TABLE IF NOT EXISTS people ( id integer PRIMARY KEY, first_name text NOT NULL, last_name text NOT NULL); """ cursor = conn.cursor() cursor.execute(sql_create_people_table) sql_truncate_people = "DELETE FROM people;" cursor.execute(sql_truncate_people)

data = generate_people(count) cursor.executemany('INSERT INTO people VALUES(?,?,?);',data);

print('We have inserted given count = ', cursor.rowcount, 'records to the table.')

conn.commit() conn.close()

# Test Case # Call create_people_database to create people table with max_people rows create_people_database(db_file=people_db_file,count=max_people)

------------------------------------------------------------------------------------

***Please make a quick FirstNames.txt (Julie, Andy, Kate) & LastNames.txt (Smith, Jordan, Mann).

***You will need to use SQLite.

Here is the original questions:

1) use "class PersonDB: "

__init__() signature:

def __init__(self, db_file=''):

  • For this method, all that needs to be done is to store the db_file parameter value into a self.db_file variable. You will use it in the __enter__() method.

__enter__() signature:

def __enter__(self):

  • __enter__ represents the method that is called when a class object of type PersonDB is used within a "with" context.
  • This method will initiate the connection to a SQLite database indicated by self.db_file.
  • Recall from Part II how to call the connect() method of sqlite3. Store the resulting connection object in a variable called self.conn.
  • Return self

__exit__() signature:

def __exit__(self, exc_type, exc_value, exc_traceback):

  • __exit__ represents the method that is called after the last line of a with block is executed.
  • This method will close the database connection by calling self.conn.close().

load_person() signature:

def load_person(self, id):

  • This method will attempt to load a "people" record with the id of "id".
  • Code a sql string to select a specific record from the database:

sql = "SELECT * FROM people WHERE id=?"

  • Open a cursor and use that cursor to execute the sql command:

cursor = self.conn.cursor()

cursor.execute(sql, (id,))

records = cursor.fetchall()

Note: the execute command accepts the sql command string and a tuple of parameters to substitute for the question marks in the command string. Notice the comma with nothing after it? That is to ensure (id,) results in a tuple, not a single evaluated value.

  • type variable called result and assign to it a tuple that represents an empty record if nothing is found in the database:

result = (-1,'','') # id = -1, first_name = '', last_name = ''

  • check to see if the "records" list contains any data and if it does get the first value out of the list. If you simply return records, you will get a list with one item in it instead of just one item.

if records is not None and len(records) > 0:

result = records[0]

cursor.close()

return result

(2) Then, code a new method outside of the class called test_PersonDB() to test load_person() using a context manager:

def test_PersonDB():

Using a "with" block with a PersonDB object, attempt to load and print three person records:

with PersonDB(people_db_file) as db:

print(db.load_person(10000)) # Should print the default

print(db.load_person(122))

print(db.load_person(300))

(3) go to the "__main__" section and call test_PersonDB() to test the method you just wrote.

The sample output would look like this:

(-1, '', '')

(122, 'ELISA', 'SINGLETON')

(300, 'GENNY', 'WEBER')

Thank you so much for your help!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!