๐Your code
SQL text + parameters
๐Driver (psycopg)
Sends SQL safely, converts types
๐PostgreSQL
Runs it inside a transaction
These examples ran against PostgreSQL 18 on this machine. The SQL itself is covered in our SQL for Data Engineers course.
Connect and create a table
import os
import psycopg
conn = psycopg.connect(os.environ["DATABASE_URL"]) # never hard-code passwords
conn.execute("""
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name TEXT NOT NULL,
city TEXT
)
""")
conn.commit()
print(conn.info.server_version // 10000, conn.info.dbname)18 shopkart_py
The connection string comes from an environment variable, never hard-coded (it contains a password in real life): postgresql://user:password@host:5432/dbname.
Insert with parameters
rows = [(1, "Asha", "Kolkata"), (2, "Rahul", "Mumbai"), (3, "Priya", "Bengaluru")]
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO customers (customer_id, name, city) VALUES (%s, %s, %s)", # placeholders
rows,
)
conn.commit()
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone())(3,)
Why never to build SQL with f-strings
name = "O'Brien"
conn.execute(f"INSERT INTO customers VALUES (4, '{name}', 'Delhi')") # โ never build SQL with f-stringsSyntaxError: syntax error at or near "Brien"
LINE 1: INSERT INTO customers VALUES (4, 'O'Brien', 'Delhi')
^An apostrophe in a real name broke the SQL. A malicious value could do far worse (SQL injection). With parameters, the driver sends the value separately, so it can never be read as SQL:
conn.rollback() # clear the failed transaction
conn.execute("INSERT INTO customers VALUES (%s, %s, %s)", (4, "O'Brien", "Delhi")) # โ
the driver escapes it
conn.commit()
print(conn.execute("SELECT name FROM customers WHERE customer_id = %s", (4,)).fetchone())("O'Brien",)Read rows as dicts
from psycopg.rows import dict_row
with conn.cursor(row_factory=dict_row) as cur:
cur.execute("SELECT customer_id, name, city FROM customers ORDER BY customer_id")
for row in cur.fetchall():
print(row){'customer_id': 1, 'name': 'Asha', 'city': 'Kolkata'}
{'customer_id': 2, 'name': 'Rahul', 'city': 'Mumbai'}
{'customer_id': 3, 'name': 'Priya', 'city': 'Bengaluru'}
{'customer_id': 4, 'name': "O'Brien", 'city': 'Delhi'}Transactions: all or nothing
try:
with conn.transaction(): # commits at the end, or rolls back on error
conn.execute("UPDATE customers SET city = 'Pune' WHERE customer_id = 2")
raise RuntimeError("something failed halfway")
except RuntimeError as e:
print("rolled back:", e)
print(conn.execute("SELECT city FROM customers WHERE customer_id = 2").fetchone())rolled back: something failed halfway
('Mumbai',)The update to Pune was undone because the block failed. Rahul is still in Mumbai.
Upsert from Python
upsert = """
INSERT INTO customers (customer_id, name, city) VALUES (%s, %s, %s)
ON CONFLICT (customer_id) DO UPDATE SET name = EXCLUDED.name, city = EXCLUDED.city
"""
with conn.cursor() as cur:
cur.executemany(upsert, [(2, "Rahul", "Pune"), (5, "Meera", "Chennai")]) # one update, one insert
conn.commit()
print(conn.execute("SELECT * FROM customers ORDER BY customer_id").fetchall())[(1, 'Asha', 'Kolkata'), (2, 'Rahul', 'Pune'), (3, 'Priya', 'Bengaluru'), (4, "O'Brien", 'Delhi'), (5, 'Meera', 'Chennai')]
Rahul moved to Pune (updated) and Meera is new (inserted). Running it again changes nothing: an idempotent load.
Bulk loading with COPY
import time
conn.execute("CREATE TABLE events (event_id INT, customer_id INT, event TEXT)")
start = time.perf_counter()
with conn.cursor() as cur:
with cur.copy("COPY events (event_id, customer_id, event) FROM STDIN") as copy:
for i in range(100_000): # COPY streams rows: the fastest way to bulk-load
copy.write_row((i, i % 5 + 1, "page_view"))
conn.commit()
print(conn.execute("SELECT COUNT(*) FROM events").fetchone()[0], "rows loaded with COPY")
print(f"took {time.perf_counter() - start:.2f}s")100000 rows loaded with COPY took 0.04s
| Method | Speed | Use for |
|---|---|---|
| execute() per row | Slowest | A handful of rows |
| executemany() | Better | Hundreds to thousands of rows |
| COPY | Fastest (100,000 rows in about 0.05 s here) | Bulk loads, staging tables |
Query results into pandas
import pandas as pd
with conn.cursor() as cur:
cur.execute("SELECT city, COUNT(*) AS customers FROM customers GROUP BY city ORDER BY city")
df = pd.DataFrame(cur.fetchall(), columns=[c.name for c in cur.description])
print(df)
conn.close()city customers 0 Bengaluru 1 1 Chennai 1 2 Delhi 1 3 Kolkata 1 4 Pune 1
Building the DataFrame from the cursor works with any driver. pd.read_sql also works, but expects a SQLAlchemy engine (or a sqlite3 connection).
SQLite: a database in one file
import sqlite3 # built into Python: a database in one file
with sqlite3.connect("shopkart.db") as db:
db.execute("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT, price REAL)")
db.executemany("INSERT INTO products (name, price) VALUES (?, ?)", [("Headphones", 1999), ("Charger", 499)])
print(db.execute("SELECT name, price FROM products ORDER BY price").fetchall())[('Charger', 499.0), ('Headphones', 1999.0)]SQLite uses ? placeholders instead of %s. Great for tests and local tools.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you prevent SQL injection in Python?Fresher+
Q2How would you load a large CSV into PostgreSQL quickly?1โ3 yrs+
Q3What is a connection pool and why use it?1โ3 yrs+
Q4How do transactions work in psycopg?1โ3 yrs+
Q5ORM or raw SQL for pipelines?3+ yrs+
Key takeaways
- โDrivers connect Python to databases; parameters keep queries safe.
- โTransactions make loads all-or-nothing.
- โUpserts make loads idempotent; COPY makes them fast.
- โNext: generators, decorators and classes, the advanced tools.
Frequently asked questions
Which library connects Python to PostgreSQL?
psycopg (version 3) is the standard PostgreSQL driver. SQLAlchemy sits on top of drivers and adds a toolkit and ORM. Other databases have their own drivers (pyodbc, snowflake-connector-python, databricks-sql-connector).
What is SQL injection?
When user or file data is pasted into SQL text, a value like ' OR 1=1 -- changes the query's meaning. Always pass values as parameters (%s placeholders) and let the driver handle quoting.
What is the fastest way to load lots of rows into PostgreSQL?
COPY. It streams rows in bulk and is many times faster than INSERT statements. psycopg 3 exposes it with cursor.copy().
Do I need to commit?
Yes. psycopg opens a transaction automatically; changes are saved only after conn.commit(), or at the end of a 'with conn:' or 'with conn.transaction():' block without errors.
When should I use SQLite?
For local tools, tests and small apps: it's built into Python, needs no server and stores the whole database in one file. Not for many concurrent writers.
๐ง Quick check: Python and databases
1. Which query is safe?
2. An error happens inside 'with conn.transaction():'. The changes are...
3. Fastest way to load 10 million rows into PostgreSQL?
4. dict_row makes rows come back as...
Checking your accessโฆ