Chapter 17
Python MySQL
9 topics · 1 sections · beginner-friendly study notes · Updated
Python talks to MySQL through a connector library (mysql-connector-python or PyMySQL).
You open a connection, get a cursor, run parameterised SQL, fetch rows, commit or roll back, and close resources.
Most business applications persist data in relational databases, and MySQL is among the most widely deployed.
Web back ends, reporting scripts, ETL jobs and admin tools that read and write MySQL tables.
Python MySQL Environment Setup
Setup means installing a MySQL server (or MariaDB), creating a user with limited privileges, and installing a Python driver such as mysql-connector-python (official, pure Python) with pip. Then verify that Python can import the driver and reach the server.
In short: Install the database, install the Python adapter, make a user, and test that they can talk.
Think about it
Most beginner errors come from wrong installs, wrong ports or missing privileges. A team shares a Docker Compose file so every developer gets the same MySQL version.
Steps
- 1install MySQL Community Server or run it in Docker (docker run -e MYSQL_ROOT_PASSWORD=secret -p 3306:3306 mysql:8);
- 2create an application user instead of using root: CREATE USER "app"@"localhost" IDENTIFIED BY "pass"; GRANT ALL ON school.
* TO "app"@"localhost"; (3) create a virtual environment and run pip install mysql-connector-python; (4) check with import mysql.
connector.
Alternatives: PyMySQL (pure Python), mysqlclient (C extension, fastest) and SQLAlchemy as an ORM on top of any driver.
Keep host, user and password in environment variables or a .
env file and never commit credentials.
MySQL 8 uses caching_sha2_password by default; modern connectors support it.
Key points
- Driver / connector: Library that speaks the MySQL protocol.
- Port 3306: Default MySQL server port.
- Virtual environment: Isolated package folder for a project.
- Environment variable: OS-level setting used to hold secrets.
Example
Code# Terminal:
# python -m venv .venv
# .venv\Scripts\activate (Windows) | source .venv/bin/activate (macOS/Linux)
# pip install mysql-connector-python
#
# SQL (run once as root):
# CREATE USER 'app'@'localhost' IDENTIFIED BY 'app_password';
# GRANT ALL PRIVILEGES ON school.* TO 'app'@'localhost';
import os
import mysql.connector
print("connector version:", mysql.connector.__version__)
CONFIG = {
"host": os.getenv("DB_HOST", "localhost"),
"port": int(os.getenv("DB_PORT", "3306")),
"user": os.getenv("DB_USER", "app"),
"password": os.getenv("DB_PASSWORD", "app_password"),
}
try:
conn = mysql.connector.connect(**CONFIG)
print("server version:", conn.get_server_info())
conn.close()
except mysql.connector.Error as err:
print("Cannot connect:", err)Database Connection
mysql.connector.connect(host, user, password, database, port) returns a connection object. conn.cursor() gives a cursor for running SQL. conn.is_connected() checks the link and conn.close() releases it. Errors derive from mysql.connector.Error.
In short: Dial the database, keep the line open while you work, hang up when done.
Think about it
Resource leaks from unclosed connections crash production services. A Flask app takes a pooled connection per request and returns it afterwards.
Always wrap connection code in try/except mysql.
connector.
Error and close both cursor and connection in finally, or use contextlib.
closing / newer context-manager support.
Common error numbers: 1045 access denied, 1049 unknown database, 2003 cannot reach server.
Opening a connection is expensive, so web apps use connection pools (mysql.
connector.
pooling.
MySQLConnectionPool) and reuse connections.
Useful options: autocommit=False (default), charset="utf8mb4", connection_timeout and use_pure.
Never build the password into source code.
A cursor is not thread-safe; use one per thread.
Key points
- Connection: Session between Python and the server.
- Cursor: Object that executes statements and holds results.
- Pool: Reusable set of open connections.
- errno: MySQL numeric error code.
Example
Codeimport mysql.connector
from mysql.connector import Error, errorcode
from contextlib import closing
CONFIG = dict(host="localhost", user="app", password="app_password", database="school")
conn = None
try:
conn = mysql.connector.connect(**CONFIG)
if conn.is_connected():
print("connected to", conn.database)
with closing(conn.cursor()) as cur:
cur.execute("SELECT VERSION()")
print("MySQL", cur.fetchone()[0])
except Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("wrong user or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("database does not exist")
else:
print("connection failed:", err)
finally:
if conn is not None and conn.is_connected():
conn.close()
print("connection closed")
# connection pool for web apps
from mysql.connector import pooling
pool = pooling.MySQLConnectionPool(pool_name="mypool", pool_size=5, **CONFIG)
pc = pool.get_connection() # borrow
# ... use pc ...
pc.close() # returns the connection to the poolCreating New Database
A database (schema) is created with the SQL statement CREATE DATABASE name. Connect WITHOUT the database argument first because the target does not exist yet, execute the statement, then optionally reconnect or run USE name. IF NOT EXISTS prevents an error when it already exists.
In short: Make an empty folder for your tables inside the MySQL server.
Think about it
Every project starts with creating its schema. Initialisation scripts that create the database on first deployment.
Syntax
CREATE DATABASE IF NOT EXISTS school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci.
utf8mb4 stores full Unicode including emoji.
List databases with SHOW DATABASES and remove one with DROP DATABASE (irreversible).
The connecting user needs the CREATE privilege.
DDL statements such as CREATE and DROP cause an implicit commit in MySQL, so they cannot be rolled back.
Database names should be lowercase with underscores to avoid case-sensitivity issues across operating systems.
Key points
- DDL: Data Definition Language: CREATE, ALTER, DROP.
- Charset utf8mb4: Full Unicode character set.
- IF NOT EXISTS: Skip creation if it already exists.
Read more
Example
Codeimport mysql.connector
conn = mysql.connector.connect(host="localhost", user="app", password="app_password")
cur = conn.cursor()
cur.execute(
"CREATE DATABASE IF NOT EXISTS school "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
cur.execute("SHOW DATABASES")
names = [row[0] for row in cur.fetchall()]
print("school" in names) # True
conn.database = "school" # switch (same as USE school)
cur.execute("SELECT DATABASE()")
print(cur.fetchone()[0]) # school
# cur.execute("DROP DATABASE school") # irreversible, be careful
cur.close()
conn.close()Creating Tables
CREATE TABLE defines columns, data types and constraints. Common types: INT, BIGINT, DECIMAL(10,2), VARCHAR(n), TEXT, DATE, DATETIME, BOOLEAN. Constraints: PRIMARY KEY, AUTO_INCREMENT, NOT NULL, UNIQUE, DEFAULT, CHECK and FOREIGN KEY.
In short: Design the spreadsheet columns and rules before you add rows.
Think about it
Good schema design prevents bugs and slow queries later. students and courses tables linked by an enrolments table.
Every table should have a primary key; AUTO_INCREMENT lets MySQL generate it.
FOREIGN KEY (student_id) REFERENCES students(id) enforces that a child row refers to an existing parent row (InnoDB engine).
Use DECIMAL, not FLOAT, for money.
Add indexes (INDEX or UNIQUE) on columns used in WHERE and JOIN.
Inspect with SHOW TABLES, DESCRIBE table or SHOW CREATE TABLE.
Change the schema using ALTER TABLE ...
ADD COLUMN / MODIFY / DROP COLUMN, and delete with DROP TABLE.
Run CREATE TABLE IF NOT EXISTS in setup scripts so they are repeatable.
Create parent tables before child tables.
Key points
- Primary key: Unique, non-
nullrow identifier. - Foreign key: Column referencing a primary key of another table.
- AUTO_INCREMENT: Automatically increasing integer.
- InnoDB: MySQL engine with transactions and foreign keys.
Read more
Example
Codeimport mysql.connector
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="school")
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(120) UNIQUE,
marks DECIMAL(5,2) DEFAULT 0,
joined DATE
) ENGINE=InnoDB
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS courses (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT NOT NULL,
title VARCHAR(80) NOT NULL,
FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE
) ENGINE=InnoDB
""")
cur.execute("SHOW TABLES")
print([r[0] for r in cur.fetchall()]) # ['courses', 'students']
cur.execute("DESCRIBE students")
for col in cur.fetchall():
print(col[0], col[1]) # id int / name varchar(100) / ...
cur.execute("ALTER TABLE students ADD COLUMN city VARCHAR(50)")
# cur.execute("DROP TABLE courses") # remove a table
cur.close(); conn.close()Insert Operation
INSERT adds rows. With the connector use cursor.execute(sql, params) with %s placeholders for one row and cursor.executemany(sql, list_of_tuples) for many rows. Changes are not permanent until conn.commit(). cursor.lastrowid returns the generated AUTO_INCREMENT id.
In short: Put values into the table through placeholders, then commit to save them.
Think about it
SQL injection via string formatting is the most serious beginner database mistake. Registration form saving a new user; CSV import saving thousands of rows with executemany.
ALWAYS pass values as the second argument; NEVER format them into the SQL string with f-strings or %, which opens the door to SQL injection (e.
g.
name = "x'; DROP TABLE students; --").
The placeholder is %s for every data type in mysql-connector (sqlite3 uses ?
).
executemany sends many rows efficiently.
INSERT IGNORE skips duplicate-key errors and INSERT ...
ON DUPLICATE KEY UPDATE implements upsert.
cursor.
rowcount tells how many rows were affected.
If an error occurs call conn.
rollback().
Autocommit is off by default, so forgetting commit() silently discards the data when the connection closes.
Key points
- Placeholder %s: Parameter marker filled safely by the driver.
commit(): Makes pending changes permanent.- lastrowid: Id generated by the last
INSERT. - SQL injection: Attack that tricks the server into running attacker SQL.
Example
Codeimport mysql.connector
from mysql.connector import Error
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="school")
cur = conn.cursor()
sql = "INSERT INTO students (name, email, marks, joined) VALUES (%s, %s, %s, %s)"
try:
cur.execute(sql, ("Ana", "ana@example.com", 72.5, "2025-01-10"))
print("new id:", cur.lastrowid) # e.g. 1
rows = [
("Raj", "raj@example.com", 35.0, "2025-01-11"),
("Lin", "lin@example.com", 90.0, "2025-01-12"),
]
cur.executemany(sql, rows)
print("inserted:", cur.rowcount) # 2
conn.commit() # make it permanent
except Error as err:
conn.rollback()
print("insert failed:", err)
finally:
cur.close()
conn.close()
# WRONG (injection risk): cur.execute(f"INSERT ... VALUES ('{name}')")
# RIGHT: cur.execute(sql, (name, ...))
# upsert example
# INSERT INTO students (email, name) VALUES (%s, %s)
# ON DUPLICATE KEY UPDATE name = VALUES(name)Read Operation
SELECT retrieves rows. After cursor.execute("SELECT ...", params) call fetchone() for the next row, fetchmany(n) for n rows or fetchall() for all remaining rows. cursor(dictionary=True) returns each row as a dict. A cursor is also iterable.
In short: Ask the question with SELECT, then pick up the answers row by row.
Think about it
Reading data and turning rows into Python objects is the most common database task. Dashboard showing the top 10 students by marks.
Select only the columns you need instead of SELECT *.
Use WHERE with parameters, ORDER BY, LIMIT/OFFSET for pagination, GROUP BY with aggregates (COUNT, AVG, MAX).
Rows are tuples by default: row[0], row[1]; with dictionary=True use row["name"].
fetchall loads everything into memory; for big result sets iterate the cursor or call fetchmany(1000) in a loop.
cursor.
description lists column names.
If you reuse a connection after a SELECT, consume or close the cursor first to avoid "Unread result found".
NULL becomes None in Python.
Decimal columns come back as decimal.
Decimal.
Key points
- fetchone / fetchall: Get the next row / all rows.
- Dictionary cursor: Rows as dicts keyed by column name.
- Pagination: Reading results in pages using LIMIT and OFFSET.
Example
Codeimport mysql.connector
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="school")
cur = conn.cursor()
cur.execute("SELECT id, name, marks FROM students ORDER BY marks DESC")
print(cur.fetchone()) # (3, 'Lin', Decimal('90.00'))
print(cur.fetchmany(1)) # next row as a list
print(cur.fetchall()) # whatever is left
print([c[0] for c in cur.description]) # ['id', 'name', 'marks']
cur.execute("SELECT name, marks FROM students WHERE marks >= %s", (50,))
for name, marks in cur: # iterate the cursor directly
print(name, marks)
dcur = conn.cursor(dictionary=True)
dcur.execute("SELECT name, marks FROM students WHERE name LIKE %s", ("A%",))
for row in dcur.fetchall():
print(row["name"], float(row["marks"])) # Ana 72.5
dcur.execute("SELECT COUNT(*) AS n, AVG(marks) AS avg_marks FROM students")
print(dcur.fetchone()) # {'n': 3, 'avg_marks': Decimal('65.833333')}
dcur.execute("SELECT name FROM students ORDER BY name LIMIT %s OFFSET %s", (2, 0))
print(dcur.fetchall()) # first page of 2 names
cur.close(); dcur.close(); conn.close()Update Operation
UPDATE modifies existing rows: UPDATE table SET col = %s WHERE condition. DELETE removes rows: DELETE FROM table WHERE condition. After executing, cursor.rowcount reports the number of affected rows and conn.commit() saves the change.
In short: Change the matching rows only, and always say which rows with WHERE.
Think about it
Accidental mass updates are a classic production incident. Updating a student marks after revaluation; deleting an unsubscribed email.
Forgetting WHERE updates or deletes EVERY row.
Test the condition with a SELECT first, and consider running statements inside a transaction so you can roll back.
Use parameters for both SET and WHERE values.
SET marks = marks + %s performs relative updates atomically on the server, avoiding a read-modify-write race.
rowcount of 0 means no row matched (or values were unchanged in MySQL).
ON DELETE CASCADE in a foreign key removes dependent child rows automatically.
Prefer soft deletes (is_deleted flag) when history matters.
TRUNCATE TABLE removes all rows quickly but cannot be rolled back.
Key points
- rowcount: Number of rows changed by the last statement.
WHERE: Filter that limits which rows are affected.- Soft delete: Mark as deleted instead of removing.
Read more
Example
Codeimport mysql.connector
from mysql.connector import Error
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="school")
cur = conn.cursor()
try:
cur.execute("UPDATE students SET marks = %s WHERE name = %s", (80, "Raj"))
print("updated rows:", cur.rowcount) # 1
cur.execute("UPDATE students SET marks = marks + %s WHERE marks < %s", (5, 40))
print("bonus rows:", cur.rowcount)
cur.execute("DELETE FROM students WHERE email = %s", ("lin@example.com",))
print("deleted rows:", cur.rowcount)
conn.commit()
except Error as err:
conn.rollback()
print("operation failed:", err)
finally:
cur.close()
conn.close()
# DANGER: UPDATE students SET marks = 0 -> changes every row!
# Safe habit: run SELECT ... WHERE first, then UPDATE with the same WHERE.Join Operation
A JOIN combines rows from two or more tables using a related column. INNER JOIN returns only matching rows; LEFT JOIN returns all rows from the left table plus matches (NULL when none); RIGHT JOIN mirrors it; CROSS JOIN gives the Cartesian product. In MySQL FULL OUTER JOIN is emulated with UNION.
In short: Stitch two tables together wherever their keys match, e.g. students with their courses.
Think about it
Relational design depends on joins, and they are asked in every database interview. Order history page: orders joined with customers and products.
Syntax
SELECT s.
name, c.
title FROM students s INNER JOIN courses c ON c.
student_id = s.
id.
Use table aliases (s, c) and qualify column names to avoid ambiguity.
LEFT JOIN plus WHERE right.
id IS NULL finds rows with no match (e.
g.
students with no course).
Combine joins with GROUP BY to aggregate: COUNT(c.
id) per student.
Index the join columns (foreign keys are indexed automatically in InnoDB) for speed.
Joins are executed by the database; avoid doing nested loops in Python that issue one query per row (N+1 problem).
Key points
- INNER
JOIN: Only rows with a match in both tables. - LEFT
JOIN: All left rows, matched right rows or NULL. - Alias: Short name for a table or column.
- N+1 problem: Running one extra query per row instead of one join.
Example
Codeimport mysql.connector
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="school")
cur = conn.cursor(dictionary=True)
cur.execute("""
SELECT s.name, c.title
FROM students AS s
INNER JOIN courses AS c ON c.student_id = s.id
ORDER BY s.name
""")
for row in cur.fetchall():
print(row["name"], "->", row["title"])
cur.execute("""
SELECT s.name, COUNT(c.id) AS course_count
FROM students s
LEFT JOIN courses c ON c.student_id = s.id
GROUP BY s.id, s.name
""")
print(cur.fetchall()) # includes students with 0 courses
cur.execute("""
SELECT s.name
FROM students s
LEFT JOIN courses c ON c.student_id = s.id
WHERE c.id IS NULL
""")
print("no course:", [r["name"] for r in cur.fetchall()])
cur.close(); conn.close()Performing Transactions
A transaction groups several statements into one atomic unit: either all succeed (COMMIT) or none do (ROLLBACK). MySQL InnoDB provides ACID transactions. In the connector autocommit is off by default, so you call conn.commit() or conn.rollback() explicitly; conn.start_transaction() begins one.
In short: Move money from A to B: take from A AND give to B, or do neither.
Think about it
Data integrity during failures is what separates toy scripts from reliable systems. Bank transfer, order placement that reduces stock and creates an invoice together.
ACID: Atomicity (all or nothing), Consistency (constraints stay valid), Isolation (concurrent transactions do not see partial work), Durability (committed data survives crashes).
Pattern
- 1try: execute statements
- 2
commit()except Error:rollback()
DDL (CREATE/ALTER/DROP) causes an implicit commit.
Savepoints (SAVEPOINT name / ROLLBACK TO name) allow partial rollback.
Isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ (MySQL default), SERIALIZABLE.
SELECT ...
FOR UPDATE locks rows to prevent concurrent changes.
Keep transactions short to reduce locking and deadlocks, and retry after a deadlock error (1213).
MyISAM tables are non-transactional.
Key points
- Atomicity: Everything in the transaction happens or nothing does.
- COMMIT / ROLLBACK: Save / undo all changes since the transaction began.
- Savepoint: Named point to roll back to inside a transaction.
- Deadlock: Two transactions waiting on each other locks.
Example
Codeimport mysql.connector
from mysql.connector import Error
conn = mysql.connector.connect(host="localhost", user="app", password="app_password", database="bank")
def transfer(src, dst, amount):
cur = conn.cursor()
try:
conn.start_transaction()
cur.execute("SELECT balance FROM accounts WHERE id = %s FOR UPDATE", (src,))
(balance,) = cur.fetchone()
if balance < amount:
raise ValueError("insufficient funds")
cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, src))
cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst))
conn.commit() # both updates saved together
print("transfer committed")
except (Error, ValueError) as err:
conn.rollback() # neither update is kept
print("transfer cancelled:", err)
finally:
cur.close()
transfer(1, 2, 500)
transfer(1, 2, 10_000_000) # fails -> rolled back
# savepoint example (inside a transaction)
# cur.execute("SAVEPOINT before_bonus")
# ... statements ...
# cur.execute("ROLLBACK TO SAVEPOINT before_bonus")
conn.close()Solved examples
Why does data inserted with Python disappear after the program ends?
Reason and fix
Formula Applied:—Approach note: Remember: execute, then commit.
Rewrite this unsafe code: cur.execute("SELECT * FROM users WHERE name = '" + name + "'").
Safe version
Formula Applied:—Approach note: The tuple needs a trailing comma when it has one item.
Write SQL to list every student with the number of courses, including students with none.
SQL query
Formula Applied:—Approach note: COUNT(*) would wrongly count 1 for unmatched rows.
Using mysql-connector style API, write the steps to connect to localhost DB school as user root, run SELECT COUNT(*) FROM students, and print the count.
Connection + query sketch
Formula Applied:—Approach note: Always close cursor/connection or use context managers when the driver supports them.
Real-world applications
Using Python MySQL in real projects
Web back ends, reporting scripts, ETL jobs and admin tools that read and write MySQL tables.
Common mistakes
❌ Myth: Using an f-string in execute() is fine for small projects.
Why this is wrong: It allows SQL injection and quoting bugs.
✅ Verified Truth: Always use %s placeholders and a parameter tuple.
⚠️ Exam Tip: Mention injection in every answer about queries.
❌ Myth: The connector commits automatically.
Why this is wrong: Autocommit is off by default.
✅ Verified Truth: Call commit(), or set autocommit=True deliberately.
⚠️ Exam Tip: Forgetting commit loses data silently.
❌ Myth: UPDATE without WHERE is harmless.
Why this is wrong: It modifies every row.
✅ Verified Truth: Always add WHERE and test with SELECT first.
⚠️ Exam Tip: Run risky statements in a transaction.
Revision notes
Python talks to MySQL through a connector library (mysql-connector-python or PyMySQL). You open a connection, get a cursor, run parameterised SQL, fetch rows, commit or roll back, and close resources.
High-Yield Quick Revision Points
- pip install mysql-connector-python; keep credentials in environment variables.
- connect() -> cursor() -> execute() -> fetch -> close in finally.
- Always use %s placeholders; never string-format SQL.
- INSERT/UPDATE/DELETE need commit(); errors need rollback().
- LEFT JOIN keeps unmatched left rows; COUNT(col) ignores NULL.
- Transactions are atomic: commit all or rollback all.
Practice questions
Which pip package is the official MySQL connector?
The placeholder used by mysql.connector is
Which method makes changes permanent?
Which JOIN returns all rows from the left table?
To undo uncommitted changes you call
Which statement creates a new database?