Connecting to MySQL with Python: A Complete Guide
MySQL is one of the most popular relational database systems, and Python offers several ways to connect to and interact with MySQL databases. In this guide, I’ll show you how to set up MySQL connections in Python, with examples from a real project.
Prerequisites
Before we begin, make sure you have:
- Python 3.9+ installed
- MySQL server installed and running
- Basic understanding of SQL
Technologies We’ll Use
- Python - Our programming language
- MySQL - Database server
- mysql-connector-python - Official MySQL driver for Python
- python-dotenv - For managing environment variables
- MasoniteORM - An elegant ORM for Python (similar to Laravel’s Eloquent)
Installation
First, let’s install the required packages:
| |
Or create a requirements.txt file:
| |
And install with:
| |
Setting Up Environment Variables
It’s best practice to keep database credentials in environment variables, not hardcoded in your application. Create a .env file in your project root:
| |
Method 1: Direct Connection with mysql-connector
Let’s start with the simplest approach using the official MySQL connector:
| |
This approach is straightforward but requires you to manage connections and write raw SQL.
Method 2: Using an ORM (MasoniteORM)
For more complex applications, an Object-Relational Mapper (ORM) can simplify database interactions. In our project, we use MasoniteORM:
Database Configuration
Create a config/database.py file:
| |
For a more environment-variable driven approach, you could do:
| |
Creating a Model
With MasoniteORM, you can define models that represent your database tables:
| |
Making Queries
Now you can use the model or query builder to interact with the database:
| |
Common Issues and Solutions
Connection Errors
If you see errors like “Can’t connect to MySQL server”, check:
- Is MySQL running?
- Are you using the correct host and port?
- Is your user/password correct?
- Does the database exist?
Security Considerations
Never commit your .env file or hardcode credentials. Always use environment variables or a secure secrets manager.
Conclusion
Connecting Python to MySQL opens up powerful possibilities for data-driven applications. Whether you choose a direct connection approach or use an ORM depends on your project’s complexity and requirements.
The examples in this guide are based on real-world usage and should help you get started with MySQL and Python integration. The combination of database access with AI capabilities (as shown in our final example) demonstrates how these technologies can work together in modern applications.
Happy coding!