Getting ready

Before using the database in our application, we need to create and populate it with some initial data. All our contacts are stored in the CSV file, so we will use a migration script to read all the records and insert them into the database.

First, we create a connection to the contacts.db file, where our data will be stored. Then, we create the contacts table with the last_name, first_name, email, and phone text fields.

Since csv.reader returns an iterable of tuples whose fields follow the same order that we have defined in our CREATE TABLE statement, we can pass it directly to the executemany method. It will execute the INSERT statement for each tuple, replacing the question marks with the actual values of each record:

import csv
import sqlite3

def main():
with open("contacts.csv", encoding="utf-8", newline="") as f,
sqlite3.connect("contacts.db") as conn:
conn.execute("""CREATE TABLE contacts (
last_name text,
first_name text,
email text,
phone text
)""")
conn.executemany("INSERT INTO contacts VALUES (?,?,?,?)",
csv.reader(f))

if __name__ == "__main__":
main()

The with statement automatically commits the transaction and closes both the file and the SQLite connection at the end of the execution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset