Chapters
Python114 chapters

Exercises

SQLite

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

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
Exercise 2

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])
Exercise 3

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])