agyanadda@gmail.com

Python with SQLite and MySQL Databases

Advanced Python 1 min read Updated Dec 4, 2026 Topic 31 of 32

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

  1. conn = sqlite3.connect("shop.db")
  2. conn.execute(sql, params)
  3. conn.commit() to save changes
  4. conn.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-python or PyMySQL — placeholders are %s
  • PostgreSQL: psycopg

For bigger apps, an ORM such as SQLAlchemy or Django ORM maps tables to Python classes.

Example

Example — A small products database Python
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

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which placeholder does sqlite3 use?

Exercise 2 True / False

You must commit (or use with conn:) to save INSERT and UPDATE changes.

Exercise 3 Fill in the Blank

Access columns by name with conn.row_factory = sqlite3.___

Frequently Asked Questions

SQLite works well for small sites with low write traffic, prototypes and desktop apps. For busy multi-user websites, use MySQL or PostgreSQL, which handle many simultaneous writes better.