← Back to Python Course | Chapter 15: Python & MySQL | Lesson 1 of 12

Python MySQL Get Started

Python does not talk to a MySQL database natively out of the box -- a separate driver package, most commonly mysql-connector-python, needs to be installed first. Once installed, connecting from a Python script follows a simple, consistent pattern: import the connector, open a connection with your credentials, and you are ready to run queries.

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

python
# 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

python
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

python
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

python
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

python
from unittest.mock import MagicMock

connect = MagicMock(return_value=MagicMock())
conn = connect(host="localhost")
conn.close()
print("Connection closed")
Common Mistakes
  1. Forgetting to install mysql-connector-python (pip install mysql-connector-python) before trying to import it, resulting in a ModuleNotFoundError.
  2. 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.
  3. 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.
Chapter Summary
  • 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.
Browser Support

mysql-connector-python is maintained by Oracle (the makers of MySQL) and supports every actively maintained Python 3 version.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.