Python MySQL Get Started
In this page:
Installing the MySQL Connector
pip install mysql-connector-python downloads and installs the official MySQL driver package, making the mysql.connector module available to import in your scripts -- this is a one-time setup step per Python environment (or virtual environment) you are working in.
Note: Install this package inside a virtual environment specific to your project, rather than globally, to keep your project's dependencies isolated and reproducible.
Warning: Forgetting this installation step and trying to import mysql.connector directly results in a ModuleNotFoundError, the most common first stumbling block for beginners.
Example: Installing the MySQL Connector
# pip install mysql-connector-python
print("Installs the mysql.connector module for your Python environment")
Establishing a Basic Connection
mysql.connector.connect(host="localhost", user="root", password="", database="mydatabase") opens a connection to a MySQL server using the given credentials, returning a connection object you will use for every subsequent query.
Note: Use "localhost" as the host when your Python script and MySQL server run on the same machine, the most common local development setup.
Warning: A wrong username, password, host, or database name produces a connection failure that should be checked and handled explicitly, not assumed to always succeed.
Example: Establishing a Basic Connection
from unittest.mock import MagicMock
# Stands in for mysql.connector.connect(), which needs a real MySQL server
connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost", user="root", password="", database="mydatabase")
print(type(conn))
Handling Connection Errors
mysql.connector.Error is the base exception class raised when a connection attempt fails -- catching it in a try-except block lets you display a clear error message and fail gracefully, instead of letting an unhandled exception crash the script.
Note: Wrap your connection attempt in a try-except block from the very start of any real script, catching mysql.connector.Error specifically to handle connection failures cleanly.
Warning: Letting a connection error propagate unhandled produces a raw traceback that can be confusing for anyone running the script without Python debugging experience.
Example: Handling Connection Errors
from unittest.mock import MagicMock
class Error(Exception):
pass
# Stands in for mysql.connector.connect() failing with mysql.connector.Error
connect = MagicMock(side_effect=Error("Access denied"))
try:
connect(host="localhost", user="root", password="wrong")
except Error as e:
print("Connection failed:", e)
Storing Credentials Securely
Database credentials should never be hardcoded directly into a script that gets committed to version control -- loading them from environment variables (using os.environ or the python-dotenv package) keeps sensitive values out of your codebase's history entirely.
Note: Use a .env file (loaded with python-dotenv) or your hosting platform's environment variable settings to keep credentials outside your committed code.
Warning: Credentials committed to version control remain in that history forever, even if removed in a later commit -- treat any accidentally-committed credential as compromised and rotate it.
Example: Storing Credentials Securely
import os
db_user = os.environ.get("DB_USER", "root")
db_password = os.environ.get("DB_PASSWORD", "")
print("Loaded credentials from environment, not hardcoded")
Closing a Connection
conn.close() explicitly closes a database connection once it is no longer needed, freeing up the resource on both the Python side and the MySQL server -- especially important in long-running scripts or ones opening many short-lived connections.
Note: Close every connection you open, ideally using a try/finally block (or a with statement, if your driver version supports it) to guarantee it closes even if an error occurs.
Warning: Leaving connections open without closing them, especially in a script that runs repeatedly or opens many connections, can exhaust the MySQL server's available connection limit over time.
Example: Closing a Connection
from unittest.mock import MagicMock
connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost")
conn.close()
print("Connection closed")
- Forgetting to install mysql-connector-python (pip install mysql-connector-python) before trying to import it, resulting in a ModuleNotFoundError.
- Hardcoding database credentials directly in a script that gets committed to version control, instead of loading them from an environment variable or a config file kept out of the repository.
- Forgetting to check the connection actually succeeded before running queries against it, leading to a confusing error later instead of a clear failure up front.
- pip install mysql-connector-python installs the official MySQL driver for Python.
- mysql.connector.connect(host=..., user=..., password=..., database=...) opens a connection and returns a connection object.
- Database credentials should be stored outside the main codebase, never hardcoded in committed source.
mysql-connector-python is maintained by Oracle (the makers of MySQL) and supports every actively maintained Python 3 version.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Python MySQL Get Started
- Python MySQL Create Database
- Python MySQL Create Table
- Python MySQL Insert Into Table
- Python MySQL Select From Table
- Python MySQL Select With a Filter
- Python MySQL Order By
- Python MySQL Delete Record
- Python MySQL Drop Table
- Python MySQL Update Table
- Python MySQL Limit
- Python MySQL Join