SQLite — built in
SQLite stores a whole database in one file and needs no server. Python includes the sqlite3 module — perfect for learning, small apps and scripts.
Steps
conn = sqlite3.connect("shop.db")conn.execute(sql, params)conn.commit()to save changesconn.close()
Using with conn: commits automatically (or rolls back on error).
Always use placeholders
conn.execute("SELECT * FROM users WHERE email = ?", (email,)) — the ? keeps you safe from SQL injection. Never build SQL with f-strings.
Reading results
fetchone(), fetchall(), or loop over the cursor. Set conn.row_factory = sqlite3.Row to access columns by name.
MySQL / PostgreSQL
- MySQL:
pip install mysql-connector-pythonorPyMySQL— placeholders are%s - PostgreSQL:
psycopg
For bigger apps, an ORM such as SQLAlchemy or Django ORM maps tables to Python classes.
Example
import sqlite3
conn = sqlite3.connect("shop.db")
conn.row_factory = sqlite3.Row
with conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
stock INTEGER DEFAULT 0
)
""")
conn.execute("DELETE FROM products")
conn.executemany(
"INSERT INTO products (name, price, stock) VALUES (?, ?, ?)",
[("Pen", 20, 100), ("Notebook", 60, 40), ("Bag", 899, 5)],
)
conn.execute("UPDATE products SET stock = stock - ? WHERE name = ?", (2, "Bag"))
max_price = 100
for row in conn.execute("SELECT name, price, stock FROM products WHERE price < ? ORDER BY price", (max_price,)):
print(f"{row['name']:<10} ₹{row['price']:>6.2f} stock {row['stock']}")
total = conn.execute("SELECT SUM(price * stock) FROM products").fetchone()[0]
print("Stock value: ₹", total)
conn.close()
Creates shop.db, inserts three products, reduces Bag stock to 3, prints Pen and Notebook (under ₹100), and Stock value: ₹ 7097.0