Python MySQL Get Started
In this page:
import mysql.connector
connection = mysql.connector.connect(
host="host", user="user", password="password"
)
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.
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.
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.
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.
Example: Storing Credentials Securely
import os
db_user = os.environ.get("DB_USER", "root") # read from the environment, not hardcoded
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.
Example: Closing a Connection
from unittest.mock import MagicMock
connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost")
conn.close() # releases the connection when it's no longer needed
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