This tutorial connects Python to MySQL with the official mysql-connector-python driver and runs the full set of CRUD operations: create a database and table, then insert, read, update and delete rows. The steps above list each operation. The sections below explain the scripts embedded at the end of the post, fix the bugs in them, and give you one complete script you can run.
Step 1 – Install MYSQL Server
- https://www.devopsschool.com/blog/how-to-download-and-install-mysql-in-macos-10/
- https://www.devopsschool.com/tutorial/mysql/how-to-install-mysql-on-centos-7.html
Step 2 – Install python mysql connector using PIP3
$ sudo pip3 install mysql-connector-python
Step 3 – Using Python – Check a mysql Connection
Step 4 – Using Python – Create a database
Step 5 – Using Python – Create a Table
Step 6 – Using Python – Insert Row Ops
Step 7 – Using Python – Read Row Ops
Step 8 – Using Python – Update Row Ops
Step 9 – Using Python – Delete Row Ops
How the example scripts map to each step
The gist embedded above contains seven small scripts, one for each step. Every script opens a connection, runs one SQL statement through a cursor and then closes the connection. Statements that change data (INSERT, UPDATE, DELETE) also call connection.commit().
| Step | Script | SQL it runs | Needs commit() |
|---|---|---|---|
| 3. Check connection | check.py | None (calls get_server_info()) | No |
| 4. Create database | createdb.py | CREATE DATABASE devopsschool1 | No (DDL) |
| 5. Create table | createtable.py | CREATE TABLE Laptop (...) | No (DDL) |
| 6. Insert | insert.py | INSERT INTO Laptop ... VALUES (%s, %s, %s, %s) | Yes |
| 7. Read | read.py | SELECT * FROM Laptop | No |
| 8. Update | update.py | UPDATE Laptop SET Name = ... WHERE id = 3 | Yes |
| 9. Delete | delete.py | DELETE FROM Laptop WHERE id = 2 | Yes |
Note: By default, mysql-connector-python sets autocommit to False. If you leave out connection.commit(), InnoDB rolls back your INSERT, UPDATE or DELETE when the connection closes, and no error is raised.
Install the driver in a virtual environment
Step 2 above runs sudo pip3 install. Current Debian, Ubuntu and Fedora releases block this with an externally-managed-environment error, and it can break Python packages the OS depends on. Install the driver in a virtual environment instead. The only package you need is the official mysql-connector-python. The comments in the gist mention mysql-connector and mysql-connector-python-rf. Both are old, unofficial packages, so don't install them.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install mysql-connector-python
# confirm the import works and print the driver version
python -c "import mysql.connector; print(mysql.connector.__version__)"Code language: PHP (php)
Create an application user and keep the password out of code
The gist connects as root and puts the password in every file. Create a dedicated user that only has rights on the tutorial database, and pass its password through environment variables. On Ubuntu, root@localhost often authenticates with the auth_socket plugin. With that plugin, a password login from Python fails with error 1045 even when the password is correct. A separate user avoids the problem.
-- run as an admin, e.g. sudo mysql
CREATE USER 'dso_app'@'localhost' IDENTIFIED BY 'Use-A-Strong-Password-1';
GRANT ALL PRIVILEGES ON devopsschool1.* TO 'dso_app'@'localhost';Code language: JavaScript (javascript)
export MYSQL_HOST=localhost
export MYSQL_USER=dso_app
export MYSQL_PASSWORD='Use-A-Strong-Password-1'Code language: JavaScript (javascript)
Note: A database-level GRANT ALL on devopsschool1.* includes permission to run CREATE DATABASE devopsschool1, so this user can run every step without global privileges.
Corrected script covering all CRUD steps
The script below replaces the seven gist files with one file. It connects before entering try, so the finally block never refers to a connection that doesn't exist. It also passes every value as a query parameter, rolls back on errors and closes the cursor before the connection. Save it as crud.py and run python crud.py.
import os
from datetime import date
from decimal import Decimal
import mysql.connector
from mysql.connector import errorcode
DB_NAME = "devopsschool1"
CONFIG = {
"host": os.environ.get("MYSQL_HOST", "localhost"),
"port": int(os.environ.get("MYSQL_PORT", "3306")),
"user": os.environ.get("MYSQL_USER", "dso_app"),
"password": os.environ["MYSQL_PASSWORD"],
}
TABLE_DDL = """
CREATE TABLE IF NOT EXISTS Laptop (
Id INT NOT NULL,
Name VARCHAR(250) NOT NULL,
Price DECIMAL(10,2) NOT NULL,
Purchase_date DATE NOT NULL,
PRIMARY KEY (Id)
)
"""
INSERT_SQL = ("INSERT INTO Laptop (Id, Name, Price, Purchase_date) "
"VALUES (%s, %s, %s, %s)")
def get_connection(database=DB_NAME):
cfg = dict(CONFIG)
if database:
cfg["database"] = database
return mysql.connector.connect(**cfg)
def run(sql, params=None, database=DB_NAME, fetch=False):
"""Run one statement. Return rows for SELECT, else affected row count."""
conn = get_connection(database) # fails here, before try, if server is down
cur = conn.cursor()
try:
cur.execute(sql, params)
if fetch:
return cur.fetchall()
conn.commit()
return cur.rowcount
except mysql.connector.Error:
conn.rollback()
raise
finally:
cur.close() # cursor first, then connection
conn.close()
def insert_laptops(rows):
conn = get_connection()
cur = conn.cursor()
try:
cur.executemany(INSERT_SQL, rows) # one transaction for all rows
conn.commit()
return cur.rowcount
except mysql.connector.Error:
conn.rollback()
raise
finally:
cur.close()
conn.close()
def main():
# Step 3: check the connection
conn = get_connection(database=None)
print("Connected to MySQL Server version", conn.get_server_info())
conn.close()
# Steps 4 and 5: create database and table (safe to re-run)
run(f"CREATE DATABASE IF NOT EXISTS {DB_NAME}", database=None)
run(TABLE_DDL)
print("Database and table ready")
# Step 6: insert
added = insert_laptops([
(2, "Area 51M", Decimal("6999.00"), date(2019, 4, 14)),
(3, "MacBook Pro", Decimal("2499.00"), date(2019, 6, 20)),
])
print(f"Inserted {added} rows")
# Step 7: read
for row in run("SELECT Id, Name, Price, Purchase_date FROM Laptop ORDER BY Id",
fetch=True):
print(row)
# Step 8: update (select the same Id you update)
changed = run("UPDATE Laptop SET Name = %s WHERE Id = %s", ("Lenovo Legion", 3))
print(f"Updated {changed} row(s):",
run("SELECT * FROM Laptop WHERE Id = %s", (3,), fetch=True))
# Step 9: delete
removed = run("DELETE FROM Laptop WHERE Id = %s", (2,))
print(f"Deleted {removed} row(s); remaining:",
run("SELECT * FROM Laptop", fetch=True))
if __name__ == "__main__":
try:
main()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Access denied: check MYSQL_USER and MYSQL_PASSWORD")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(f"MySQL error: {err}")
raise SystemExit(1)Code language: PHP (php)
The database name in CREATE DATABASE is built with an f-string because identifiers (database, table and column names) can't be passed as %s parameters. Only do this with a constant you control, never with user input. Values such as names, prices, dates and IDs should always go through the params tuple. The driver then escapes them, which prevents SQL injection.
Expected output
On a clean database, the script prints something like the output below. The server version will differ. The driver returns DECIMAL columns as Python Decimal and DATE columns as datetime.date.
Connected to MySQL Server version 8.0.xx
Database and table ready
Inserted 2 rows
(2, 'Area 51M', Decimal('6999.00'), datetime.date(2019, 4, 14))
(3, 'MacBook Pro', Decimal('2499.00'), datetime.date(2019, 6, 20))
Updated 1 row(s): [(3, 'Lenovo Legion', Decimal('2499.00'), datetime.date(2019, 6, 20))]
Deleted 1 row(s); remaining: [(3, 'Lenovo Legion', Decimal('2499.00'), datetime.date(2019, 6, 20))]Code language: JavaScript (javascript)
Note: Row 3 is still in the table after the first run, so a second run fails with error 1062 (Duplicate entry '3' for key PRIMARY). Run DELETE FROM Laptop; or DROP TABLE Laptop; before running the script again.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
NameError: name 'connection' is not defined | In the gist scripts, connect() failed, and then finally used the variable anyway | Connect before try, or set connection = None first and check for it in finally |
error: externally-managed-environment | You ran pip install against the system Python | Use a virtual environment, as shown above |
ModuleNotFoundError: No module named 'mysql' | The package is installed for a different interpreter | Install with python -m pip from the interpreter that runs the script |
1045 (28000): Access denied | Wrong credentials, or root uses auth_socket | Check the environment variables, or use the dedicated user |
2003 (HY000): Can't connect to MySQL server | The server isn't running, or the host or port is wrong | Run systemctl status mysqld (or mysql) and check MYSQL_HOST and MYSQL_PORT |
Authentication plugin 'caching_sha2_password' is not supported | The old mysql-connector package is installed | Run pip uninstall mysql-connector, then install mysql-connector-python |
1007 database exists / 1050 table exists | You re-ran the create scripts | Use IF NOT EXISTS |
| Inserted rows disappear | commit() is never called | Call connection.commit() after each write |
Best practices for Python and MySQL code
- Always use parameters (
%splus a tuple) for values. Don't build SQL with string formatting. - Commit or roll back explicitly. Put related writes in one transaction so they either all apply or none do.
- Use
executemany()for bulk inserts. It is much faster than callingexecute()in a Python loop. - Use
DECIMALfor money.FLOATstores approximate values, so prices can come back with rounding errors. - Fetch only what you need. Name the columns instead of using
SELECT *, and usefetchone()orfetchmany()for large result sets. - Reuse connections in long-running apps with
mysql.connector.pooling.MySQLConnectionPool. Opening a new connection for every query is slow. - Grant least privilege. The application user should only have rights on its own schema, never
root.
For more database and scripting guides, see the SQL & MySQL tutorials and Python tutorials.
Frequently asked questions
Which Python package should I use to connect to MySQL?
Use mysql-connector-python, the official driver from Oracle. You import it with import mysql.connector. PyMySQL and mysqlclient also work, but their APIs differ slightly. The mysql-connector and mysql-connector-python-rf packages are outdated and you should not use them.
Why are my INSERT or UPDATE changes not saved?
Autocommit is off by default in mysql-connector-python. Call connection.commit() after write statements, or pass autocommit=True to connect() if you really want every statement committed on its own.
How do I prevent SQL injection in Python MySQL queries?
Pass values separately from the SQL, as in cursor.execute("SELECT * FROM Laptop WHERE Id = %s", (laptop_id,)). The driver escapes the values. Never insert user input into the SQL string with f-strings or format().
Why does cursor.rowcount return 0 after an UPDATE?
By default, MySQL reports rows that actually changed. If the new value is the same as the old one, or no row matches the WHERE clause, rowcount is 0.
How do I get the auto-generated ID after an INSERT?
If the table has an AUTO_INCREMENT primary key, read cursor.lastrowid right after execute(). The Laptop table in this tutorial sets Id explicitly, so it doesn't need this.
Related tutorials
- More SQL & MySQL tutorials
- More Python tutorials
- Datadog Tutorials: Datadog Agent integration with mysql databases?
- Top 50 Python Interview Questions and Answers
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals
Good coverage of basic PythonโMySQL operations, but one real-world gap is production-grade database handling. In actual systems, direct raw queries with basic connectors can quickly become risky without connection pooling, retry logic, and proper transaction management. Also, error handling and rollback strategies are criticalโespecially when multiple writes are involved, otherwise partial failures can corrupt business data. In CI/CD-driven environments, teams usually abstract DB access through ORM layers or service APIs instead of tightly coupling scripts directly to MySQL connections.