Databases and SQLite
Connect to relational databases, execute SQL queries safely with parameterized statements, handle transactions, and persist data using Python's built-in sqlite3.
When building real-world software, saving data into flat text files (files) or JSON files (json-csv) quickly hits a hard ceiling:
- How do you find a single user out of 5,000,000 records without loading the entire 4 GB file into RAM?
- What happens if two users update their account balance at the exact same millisecond? Flat files get corrupted.
- What if your server loses power halfway through saving a bank transfer?
This is why Relational Databases (RDBMS) exist. A relational database stores structured tables of data, provides lightning-fast lookups via indexes, enforces rules (like unique emails), and guarantees ACID transactions (Atomicity, Consistency, Isolation, Durability) so data is never half-saved or corrupted.
Python comes out of the box with sqlite3, a complete, zero-configuration SQL database engine that requires no external servers or background services.
Understanding SQLite
Unlike databases such as PostgreSQL or MySQL that run as independent client-server network applications, SQLite is an embedded database engine. Your entire database lives inside a single file on your hard drive (e.g. app.db).
Every iPhone, Android phone, Mac, and web browser in the world has SQLite embedded inside it. In Python, you interact with it using standard SQL (Structured Query Language).
Python Application
│
▼ (Python sqlite3 library)
[ Cursor ] ──► Executes SQL: "SELECT * FROM users WHERE age > 21"
│
▼
[ app.db File ] (Tables, rows, indexes stored on local disk)
The Fundamental Database Workflow
Working with any SQL database in Python follows four core steps:
- Connect: Open a connection to the database file (or
":memory:"for instant temporary testing in RAM). - Create a Cursor: A cursor acts like a pointer that executes queries and retrieves results.
- Execute SQL: Send
CREATE,INSERT,UPDATE, orSELECTcommands. - Commit & Close: Permanently save pending transactions to disk and close the connection.
Here is a complete, working example:
import sqlite3
# 1. Connect to an in-memory database for testing
connection = sqlite3.connect(":memory:")
# 2. Create a cursor
cursor = connection.cursor()
# 3. Create a table
cursor.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
points INTEGER DEFAULT 0
)
""")
# 4. Insert data using parameterized placeholders (?)
cursor.execute(
"INSERT INTO users (name, email, points) VALUES (?, ?, ?)",
("Ada Lovelace", "ada@example.com", 150)
)
cursor.execute(
"INSERT INTO users (name, email, points) VALUES (?, ?, ?)",
("Alan Turing", "alan@example.com", 220)
)
# 5. Commit changes to save them
connection.commit()
# 6. Query data
cursor.execute("SELECT id, name, points FROM users WHERE points > ?", (100,))
rows = cursor.fetchall()
for row in rows:
print(f"ID: {row[0]} | User: {row[1]} | Score: {row[2]}")
connection.close()
Output:
ID: 1 | User: Ada Lovelace | Score: 150
ID: 2 | User: Alan Turing | Score: 220
The Golden Rule: Prevent SQL Injection
The single most dangerous security vulnerability in backend programming is SQL Injection. It happens when a developer uses string concatenation or f-strings to inject user input directly into an SQL command:
# FATAL SECURITY FLAW — NEVER DO THIS!
user_input = "alice' OR '1'='1"
query = f"SELECT * FROM users WHERE username = '{user_input}'"
# The query becomes: SELECT * FROM users WHERE username = 'alice' OR '1'='1'
# The attacker bypasses authentication and accesses every account!
The Safe Solution: Parameterized Queries
Always use question mark placeholders (?) and pass the values as a tuple in the second argument. Python and SQLite will automatically sanitize and escape the input:
# SAFE AND SECURE:
cursor.execute(
"SELECT * FROM users WHERE username = ? AND password = ?",
(user_input, password_input)
)
[!NOTE] When passing a single parameter, remember that Python requires a trailing comma to make a one-item tuple:
(user_id,). If you write(user_id), Python evaluates it as a plain integer or string, causing aTypeError: parameters are of unsupported type.
Convenient Data Access with Row Factory
By default, SQLite queries return plain tuples (row[0], row[1]), which can make your code brittle if column orders change. You can set the connection’s row_factory to sqlite3.Row to access columns by their database column names like a dictionary:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row # Enables column-name dictionary access
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (id INTEGER, name TEXT, price REAL)")
cursor.execute("INSERT INTO products VALUES (1, 'Mechanical Keyboard', 89.99)")
conn.commit()
cursor.execute("SELECT name, price FROM products WHERE id = ?", (1,))
product = cursor.fetchone()
print(f"Product: {product['name']}, Cost: ${product['price']:.2f}")
# Output: Product: Mechanical Keyboard, Cost: $89.99
Context Managers for Safe Connection Handling
Just like opening files with with open(...), connections can be managed with with blocks (context-managers). When used as a context manager, SQLite automatically commits transactions if no errors occurred, or rolls them back if an exception was raised:
import sqlite3
def register_user(db_path: str, username: str, email: str) -> bool:
try:
# The 'with conn' block handles automatic commit / rollback
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO users (username, email) VALUES (?, ?)",
(username, email)
)
# Automatic commit happens here upon normal exit
return True
except sqlite3.IntegrityError:
print(f"Error: Email {email} is already registered!")
return False
Transactions and the ACID Guarantee
Imagine transferring $100 from Alice to Bob:
- Deduct $100 from Alice’s account.
- Add $100 to Bob’s account.
If a network error or power cut strikes right after Step 1, Alice lost $100 and Bob never received it!
A Transaction ensures that either all statements succeed, or none of them do:
import sqlite3
conn = sqlite3.connect("bank.db")
cursor = conn.cursor()
try:
cursor.execute("UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice'")
cursor.execute("UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob'")
conn.commit() # Both operations saved together atomically
print("Transfer successful!")
except Exception as error:
conn.rollback() # Undo any half-completed changes
print("Transfer failed. Rolled back all changes:", error)
finally:
conn.close()
Moving to Production: ORMs vs Raw SQL
For microservices or local utilities, built-in sqlite3 is fast and lightweight. But as projects grow to multiple developers and dozens of tables, developers often use:
- Production Databases: PostgreSQL or MySQL running on dedicated servers, using drivers like
psycopg3orasyncpg. - Object-Relational Mappers (ORMs): Libraries like SQLAlchemy, SQLModel, or the Django ORM (django) that let you define database tables as Python classes and automatically generate the SQL queries for you:
# Conceptual example with an ORM (SQLAlchemy / SQLModel)
class User(Model):
id: int
name: str
email: str
# Instead of raw SQL strings, you write Python:
users = session.query(User).filter(User.name == "Alice").all()
Common Traps to Avoid
- Forgetting
conn.commit(): You run anINSERTstatement, your script finishes with code 0, but when you check the database later, the table is empty! In SQLite, data modifications exist only in temporary memory until you callconn.commit(). - Using f-strings in queries: Never do
f"SELECT * FROM users WHERE id = {user_id}". It opens your application to catastrophic SQL injection attacks. Always usecursor.execute("... WHERE id = ?", (user_id,)). - Database is locked (
OperationalError): SQLite allows unlimited simultaneous readers, but only one writer at a time. If you leave a connection open in another tool or thread, other writes will fail withdatabase is locked. Always close your connections or use context managers.
Once your application can store and query data safely, the next step is connecting it to the outside world by fetching and sending data over web APIs with http-requests.