Practice: Database Connections
Q1. Open and read
Open an in-memory database, run `SELECT 5 + 3` and print the result number.
Goal: Open a connection.
Q2. Create a file database
Connect to a file `notes.db`, create table `notes(text TEXT)`, insert one note, commit, close, then check with os.path.exists and print the result.
Goal: Use file databases.
Q3. Persist across connections
Write data to a file database, close it, reopen it and print the stored value.
Goal: Understand persistence.
Q4. Close with closing
Use `contextlib.closing` to open an in-memory database, create a table, insert one row and print the row count.
Goal: Close connections safely.
Q5. Names with Row
Create a table `pets(name, legs)`, insert ('dog', 4), set row_factory to sqlite3.Row and print `dog has 4 legs` using column names.
Goal: Use row_factory.
Q6. Read in chunks
Insert numbers 1 to 6 into a table. Fetch the first two rows with fetchmany(2), then print the remaining rows as a list of numbers.
Goal: Control fetching.
Q7. Separate memory databases
What does this print?
import sqlite3
a = sqlite3.connect(':memory:')
b = sqlite3.connect(':memory:')
a.execute('CREATE TABLE t (x)')
try:
b.execute('SELECT * FROM t')
except sqlite3.OperationalError:
print('separate')Goal: Know memory isolation.
Q8. Cursor position
What does this print?
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (n)')
conn.executemany('INSERT INTO t VALUES (?)', [(1,), (2,), (3,)])
cur = conn.execute('SELECT n FROM t ORDER BY n')
print(cur.fetchone())
print(cur.fetchone())Goal: Follow cursor position.
Q9. Use after close
What does this print?
import sqlite3
conn = sqlite3.connect(':memory:')
conn.close()
try:
conn.execute('SELECT 1')
except sqlite3.ProgrammingError:
print('closed')Goal: Recognise closed connections.
Q10. Row keys
What does this print?
import sqlite3
conn = sqlite3.connect(':memory:')
conn.row_factory = sqlite3.Row
conn.execute('CREATE TABLE t (a, b)')
conn.execute('INSERT INTO t VALUES (1, 2)')
r = conn.execute('SELECT a, b FROM t').fetchone()
print(r.keys(), r['b'])Goal: Inspect Row objects.
Q11. Description
What does this print?
import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.execute('SELECT 1 AS one, 2 AS two')
print([d[0] for d in cur.description])Goal: Read cursor metadata.
Q12. Output of with conn
What does this print?
import sqlite3
conn = sqlite3.connect(':memory:')
with conn:
conn.execute('CREATE TABLE t (x)')
conn.execute('INSERT INTO t VALUES (1)')
print(conn.execute('SELECT COUNT(*) FROM t').fetchone()[0])Goal: Know what with conn does.
Q13. Fix the folder error
This code fails because the folder `data` does not exist. Fix it so it prints True.
import sqlite3, os
conn = sqlite3.connect('data/app.db')
conn.execute('CREATE TABLE t (x)')
conn.commit()
conn.close()
print(os.path.exists('data/app.db'))Goal: Prepare paths.
Q14. Fix the missing close
This function opens a connection and leaves it open if an error happens. Rewrite it with try/finally so the connection always closes, and print closed ok.
import sqlite3
def count_rows():
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (x)')
n = conn.execute('SELECT COUNT(*) FROM t').fetchone()[0]
conn.close()
return n
print(count_rows())Goal: Clean up resources.
Q15. Connection versus cursor
Explain in your own words the difference between a connection and a cursor, and say what with conn: does.
Goal: Distinguish key objects.
Q16. Safe config opener
Write a function `open_db(path)` that returns a connection with row_factory set to sqlite3.Row. Use ':memory:' to test it and print the type name of the connection.
Goal: Build helper functions.