0%

When a File Is No Longer Enough · practice

Connect Python to SQLite

Your SQL query is ready, but Python must open the database before that query can run. The sqlite3 gives you the you need:

import sqlite3

connection = sqlite3.connect(":memory:")

sqlite3.connect() returns a connection. A connection is the Python your program uses to talk to an SQLite database. It is not a copy of the data, and it is not the database itself.

The special text :memory: tells SQLite to keep this small database in memory instead of creating a file. It lasts while the connection is open and disappears when the connection closes, which makes it useful for practice.

Open the connection yourself

The editor has opened connect.py. Most of the program is already there so you can focus on one new line. Find this placeholder:

connection = None

Replace None with sqlite3.connect(":memory:"), then press Run.

Run may also show work from earlier lessons. Find the == connect.py == heading. When the item names appear beneath it, trace what the existing lines did: they prepared the familiar items table, ran query.sql, printed the answer, and reached this final line:

connection.close()

Opening a connection gives Python access to the database. Closing it tells SQLite that this program is finished with that connection.

If the call still feels unfamiliar, ask Monty:

What does sqlite3.connect(":memory:") return, and how is that different from the database?

What is the connection created by sqlite3.connect(":memory:")?

Python has now opened a real SQLite database, used your SQL query, and closed the connection. One question remains: did closing end only the connection, or did it erase the data too?

Task

In connect.py, replace None with sqlite3.connect(":memory:"). Leave the other lines as they are.

Run the project and find the == connect.py == section. You should see the names returned by query.sql. Then submit your work.