Exercises
SQLite
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Create the table, insert one row, and print everything back.
Python
import sqlite3
connection = sqlite3.connect(":memory:")
# create people(name, born), insert Ada 1815, then select all
execute the CREATE, then the INSERT, then the SELECT.
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE people (name TEXT, born INTEGER)")
connection.execute("INSERT INTO people VALUES (?, ?)", ("Ada", 1815))
print(connection.execute("SELECT * FROM people").fetchall())Exercise 2Passed
This builds SQL by formatting. Rewrite it with a placeholder.
Python
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE people (name TEXT, born INTEGER)")
connection.executemany("INSERT INTO people VALUES (?, ?)", [("Ada", 1815), ("Grace", 1906)])
year = 1900
cursor = connection.execute(f"SELECT name FROM people WHERE born > {year}")
print([row[0] for row in cursor])Use ? and pass the value in a tuple.
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE people (name TEXT, born INTEGER)")
connection.executemany("INSERT INTO people VALUES (?, ?)", [("Ada", 1815), ("Grace", 1906)])
year = 1900
cursor = connection.execute("SELECT name FROM people WHERE born > ?", (year,))
print([row[0] for row in cursor])Exercise 3Passed
Read the row by column name instead of by position.
Python
import sqlite3
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE people (name TEXT, born INTEGER)")
connection.execute("INSERT INTO people VALUES (?, ?)", ("Ada", 1815))
row = connection.execute("SELECT * FROM people").fetchone()
print(row[0], row[1])Set connection.row_factory before querying.
import sqlite3
connection = sqlite3.connect(":memory:")
connection.row_factory = sqlite3.Row
connection.execute("CREATE TABLE people (name TEXT, born INTEGER)")
connection.execute("INSERT INTO people VALUES (?, ?)", ("Ada", 1815))
row = connection.execute("SELECT * FROM people").fetchone()
print(row["name"], row["born"])