How do I connect to a MySQL Database in Python?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Connecting Python to MySQL is usually straightforward once you choose a driver and keep credentials, queries, and cleanup under control. The most common approach is to use a DB-API compatible driver such as mysql-connector-python or PyMySQL, then execute parameterized SQL through a cursor.
Install A Driver First
One popular driver is Oracle's connector:
After installation, a basic connection looks like this:
This opens a TCP connection to MySQL and selects the database immediately.
Run Queries With A Cursor
Once connected, create a cursor and execute SQL:
For inserts or updates, call commit():
Using placeholders such as %s is important. It keeps values separate from the SQL text and helps prevent injection bugs.
Prefer Parameterized Queries
Do not build SQL by concatenating user input:
That pattern is safer and avoids quoting mistakes. It also lets the driver convert Python values into MySQL-friendly forms.
Handle Errors And Cleanup Explicitly
Database code should clean up cursors and connections even when something fails:
The dictionary=True option is useful if you want rows as dictionaries instead of tuples.
Consider SQLAlchemy For Larger Projects
If the project grows, SQLAlchemy can manage engines, transactions, pooling, and ORM models. Even when you do not use the ORM, its connection layer is useful:
For small scripts, a direct connector is usually enough. For larger applications, SQLAlchemy reduces repeated connection boilerplate.
Localhost, Ports, And Remote Servers
Most connection failures are not Python syntax problems. They are usually one of these:
- wrong host or port
- invalid username or password
- MySQL not listening for TCP connections
- the user not being allowed from the client host
If you are running Python in Docker, 127.0.0.1 may be wrong because the database may live in another container. In that case, connect using the service name on the Docker network instead.
It is also a good habit to keep connection settings in environment variables instead of embedding them directly in source code. That makes local development, CI, and production deployment easier to configure without editing the script itself.
Common Pitfalls
One common mistake is interpolating values directly into SQL strings instead of using parameterized queries.
Another issue is forgetting connection.commit() after inserts, updates, or deletes, which makes it look like the statement ran but saved nothing.
A third problem is leaking cursors or connections by returning early from a function without cleanup.
Finally, developers often debug the Python code first when the real problem is MySQL permissions, host binding, or firewall access.
Summary
- Install a MySQL driver such as
mysql-connector-pythonbefore connecting. - Use
mysql.connector.connect(...)with host, user, password, and database settings. - Execute SQL through a cursor and use placeholders for parameters.
- Call
commit()for writes and always close cursors and connections. - For larger applications, consider SQLAlchemy for cleaner connection and transaction management.
Related reading
- How do I connect to a MySQL Database in Python?
- How do I connect to a MySQL Database in Python?
- How do I connect to mongodb with node.js and authenticate?
- How do I convert from BLOB to TEXT in MySQL?
- How do I convert a IPython Notebook into a Python file via commandline?
- How do I convert a numpy array to and display an image?
- How do I copy a database from one MongoDB server to another?
- How do I create a new database in MongoDB using PyMongo?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.