MySQL Get Started
Learn how to connect Python to a MySQL database using mysql-connector-python. Covers installation, connecting, creating databases, and running queries.
Python can talk to MySQL databases through the official MySQL Connector/Python driver. This chapter shows you how to install the driver, establish a connection, create a database, and run your first queries — giving you a solid foundation before moving on to creating tables, inserting rows, and querying data.
What You Need
Before writing any code you need two things in place:
- Python 3.7 or later installed on your machine.
- A running MySQL server — either a local installation (MySQL Community Server) or a cloud instance (PlanetScale, Amazon RDS, etc.).
You do not need to create a database ahead of time; you will create one from Python in a later section.
Installing MySQL Connector/Python
MySQL Connector/Python is the official MySQL driver maintained by Oracle. Install it with pip:
pip install mysql-connector-pythonVerify the installation:
import mysql.connector
print(mysql.connector.__version__)
# Example output: 8.4.0If you see a version number, the driver is ready to use.
Why mysql-connector-python and not PyMySQL?
Both drivers work, but mysql-connector-python is the officially supported driver from Oracle. It uses a pure-Python implementation by default and optionally a C extension for better performance. PyMySQL is a popular community alternative with a nearly identical API. The chapters in this section use mysql-connector-python.
Connecting to a MySQL Server
Use mysql.connector.connect() to open a connection. Pass your credentials as keyword arguments:
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
if connection.is_connected():
print("Connected to MySQL Server")
connection.close()Replace yourusername and yourpassword with your actual credentials. The host value is "localhost" when MySQL runs on the same machine; use an IP address or hostname for a remote server.
Keeping credentials out of source code
Hard-coding passwords in scripts is a security risk. Store them in environment variables and read them at runtime:
import mysql.connector
import os
connection = mysql.connector.connect(
host=os.environ.get("MYSQL_HOST", "localhost"),
user=os.environ.get("MYSQL_USER"),
password=os.environ.get("MYSQL_PASSWORD")
)
print("Connected:", connection.is_connected())
connection.close()Set the variables in your shell before running the script:
export MYSQL_USER=yourusername
export MYSQL_PASSWORD=yourpassword
python connect.pyCreating a Database
Once connected to the server (without specifying a database), you can create one with a CREATE DATABASE statement. Execute it through a cursor — an object that sends SQL commands and retrieves results.
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS mydatabase")
print("Database created")
cursor.close()
connection.close()The IF NOT EXISTS clause prevents an error if the database already exists.
Listing databases
You can verify the database was created by listing all databases on the server:
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
cursor = connection.cursor()
cursor.execute("SHOW DATABASES")
for db in cursor:
print(db)
cursor.close()
connection.close()Each row is returned as a tuple, so you will see output like:
('information_schema',)
('mydatabase',)
('mysql',)
('performance_schema',)
('sys',)Connecting to a Specific Database
Once the database exists, include the database parameter when connecting so all subsequent queries run against it:
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
print("Database in use:", connection.database)
connection.close()Using a Context Manager (Recommended Pattern)
Manually calling .close() on every connection and cursor is error-prone — if an exception occurs before .close(), the connection leaks. Use a try/finally block, or better, wrap the cursor in a with statement:
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
try:
with connection.cursor() as cursor:
cursor.execute("SELECT DATABASE()")
row = cursor.fetchone()
print("Current database:", row[0])
finally:
connection.close()The with block closes the cursor automatically when the block exits, even if an exception is raised.
Handling Connection Errors
Network issues or wrong credentials raise mysql.connector.Error. Always handle this exception in production code:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
print("Connection successful")
except Error as e:
print(f"Error connecting to MySQL: {e}")
finally:
if "connection" in dir() and connection.is_connected():
connection.close()
print("Connection closed")Common errors you may encounter:
| Error code | Meaning |
|---|---|
| 1045 | Access denied — wrong username or password |
| 2003 | Cannot connect to host — server not running or wrong host/port |
| 1049 | Unknown database — the database name does not exist |
Quick Reference: Connection Parameters
| Parameter | Type | Description |
|---|---|---|
host | str | MySQL server hostname or IP (default "127.0.0.1") |
port | int | MySQL port (default 3306) |
user | str | MySQL username |
password | str | MySQL password |
database | str | Database to select on connect |
charset | str | Character set (default "utf8mb4") |
connect_timeout | int | Seconds to wait for connection (default 10) |
use_pure | bool | True = pure Python; False = C extension if available |
What Comes Next
With a working connection in place you are ready to build on it:
- Create a table — define columns and data types with
CREATE TABLE. - Insert rows — add data with
INSERT INTOand parameterized queries. - Query data — retrieve rows with
SELECT,fetchone(), andfetchall(). - Filter rows — narrow results with
WHEREclauses. - Create a database — full walkthrough of the
CREATE DATABASEcommand.