iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python SQLite

SQLite is a single-file SQL database. The driver — sqlite3 — ships with Python, so there's nothing to install.

Connect

PYTHON
import sqlite3

con = sqlite3.connect('shop.db')      # file on disk
# or
con = sqlite3.connect(':memory:')     # in-memory, gone on close

Create + insert + read

PYTHON
con = sqlite3.connect(':memory:')
con.executescript('''
  CREATE TABLE customers (
    id   INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE
  );
''')

con.execute('INSERT INTO customers (name, email) VALUES (?, ?)',
            ('Ada', 'ada@example.com'))
con.commit()

for row in con.execute('SELECT * FROM customers'):
    print(row)
con.close()

Row factory — dict-style rows

PYTHON
con.row_factory = sqlite3.Row
for row in con.execute('SELECT id, name FROM customers'):
    print(row['name'])    # access by column name

Use parameter binding

PYTHON
# ✗ Don't
con.execute(f"SELECT * FROM users WHERE email = '{email}'")

# ✓ Do
con.execute('SELECT * FROM users WHERE email = ?', (email,))

Transactions

PYTHON
with con:           # con as context manager = transaction
    con.execute('UPDATE accounts SET bal = bal - 100 WHERE id = 1')
    con.execute('UPDATE accounts SET bal = bal + 100 WHERE id = 2')
# Auto-commit on clean exit; rollback if an exception propagated.

Where SQLite shines

  • Tests — way faster than spinning up MySQL/Postgres in CI.
  • Desktop / mobile apps — one file, no server.
  • Caching, config, small embedded data.
  • Local prototyping before deciding on a real DB.
Tip: Even for "throwaway" demos, prefer parameter-bound queries. Once the demo turns into a "thing", you don't have an injection bug to hunt.

Example

Example
import sqlite3
con = sqlite3.connect(':memory:')
con.executescript('''
  CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
  INSERT INTO customers (name) VALUES ('Ada'), ('Linus');
''')
for row in con.execute('SELECT * FROM customers'):
    print(row)
Try it Yourself »

Exercise

Connect to an in-memory SQLite database.

sqlite3.connect(' ')

Test yourself

Q1. The sqlite3 module is…
Q2. For an in-memory DB use…
Q3. Parameter placeholder is…

Discussion

Loading…