PYTHON SQLITE · LESSON 1 OF 4

Connect and query

Create a small in-memory database and read rows by column name.

Run this script with Python 3.12 or newer. It creates a disposable database, adds two books and prints their titles. Replace :memory: with a file path when you want persistence. A context manager commits successful work or rolls back a failed transaction; closing the connection is a separate step.

Run it on your computer

python3 connect-and-query.py

Requires Python 3.12+. The script creates its own in-memory sample. It does not read your browser database or upload anything.

import sqlite3

con = sqlite3.connect(":memory:", autocommit=False)
con.row_factory = sqlite3.Row
try:
    with con:
        con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT)")
        con.executemany("INSERT INTO books (title) VALUES (?)", [("SQL notes",), ("Data diary",)])
    for row in con.execute("SELECT id, title FROM books ORDER BY id"):
        print(row["id"], row["title"])
finally:
    con.close()

Expected output

1 SQL notes
2 Data diary

Try a change

Change the SELECT to return only the second book. Keep ORDER BY when your result order matters.

Practice SQL in the browser or use the Python sqlite3 documentation for API details.

Next: Bind values safely →