What Flask and MySQL are, and why you connect them
Flask is a Python web framework — a set of tools that lets you build websites and web applications. MySQL is a database, which is where your process stores information like user accounts, posts, or product listings. When you connect Flask to MySQL, your web process can read from and write to that database, so the data persists even after someone closes their browser.
Without a database connection, your Flask app can only work with information that exists in the current session. The moment a user leaves, that data is gone. MySQL lets you keep it permanently and retrieve it later.
Key Takeaways
- Flask needs a driver called mysql-connector-python or PyMySQL to communicate with MySQL at all.
- You store your database name, username, and password in your Flask configuration, never hardcoded into your process files.
- The connection happens through a single line of code that creates a cursor object, which you then use to send SQL commands to the database.
- Most Flask projects use an extension called Flask-SQLAlchemy instead of raw MySQL connections, because it handles common problems automatically.
Installing the MySQL driver your Flask app needs
Flask itself does not know how to talk to MySQL. You need a driver — a piece of software that translates Flask's requests into language MySQL understands. The two most common drivers are mysql-connector-python (made by MySQL) and PyMySQL (made by the open-source community).
Open your terminal or command prompt and install one of them. If you are using mysql-connector-python, type:
pip install mysql-connector-python
If you prefer PyMySQL, type:
pip install PyMySQL
Both work equally well for most projects. PyMySQL is slightly lighter and faster; mysql-connector-python is the official option from the MySQL team. Pick one and stick with it — you do not need both.
Setting up your connection details in Flask configuration
Your Flask app needs to know where the database lives, what it is called, and what username and password to use. You store these in your Flask configuration file, not scattered through your code. This keeps sensitive information in one place and makes it straightforward to change later.
Create a file called config.py in your project folder. Inside it, write:
MYSQL_HOST = 'localhost' MYSQL_USER = 'your_username' MYSQL_PASSWORD = 'your_password' MYSQL_DATABASE = 'your_database_name'
Replace your_username, your_password, and your_database_name with the actual values you set up in MySQL. If your database is on a different computer, replace localhost with that computer's address.
Then in your main Flask file (usually app.py), import this configuration at the top:
from config import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE
Creating the actual connection and running a query
Once your driver is installed and your configuration is loaded, you create a connection object. This object represents the open line of communication between Flask and MySQL. Here is the basic pattern using mysql-connector-python:
import mysql.connector connection = mysql.connector.connect( host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE ) cursor = connection.cursor() cursor.execute("SELECT * FROM users") results = cursor.fetchall() cursor.close() connection.close()
The cursor is the tool you use to send SQL commands. execute() sends a command to the database. fetchall() retrieves all the rows that came back. When you are done, you close the cursor and the connection to free up resources.
If you are using PyMySQL instead, the pattern is nearly identical — only the import line changes to import pymysql and the connection call becomes pymysql.connect().
Why Flask-SQLAlchemy is the better choice for most projects
Writing raw MySQL connections like the example above works, but it is repetitive and error-prone. Most Flask projects use an extension called Flask-SQLAlchemy, which handles the connection, cursor management, and common problems automatically.
Install it with:
pip install Flask-SQLAlchemy
Then set it up in your Flask app:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost/database_name' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) email = db.Column(db.String(120)) users = User.query.all()
Flask-SQLAlchemy lets you define your database tables as Python classes, then query them using Python instead of writing SQL. It also manages the connection pool, handles disconnections, and prevents common security problems. For anything beyond a straightforward test, this is the standard approach.
Common problems and what causes them
The most frequent error is "Access denied for user" — this means your username or password is wrong, or the user does not have permission to access that database. Check your MySQL user setup and make sure the credentials in your config file match exactly.
"Unknown database" means the database name is misspelled or does not exist. Log into MySQL directly and run SHOW DATABASES; to see what databases actually exist.
"Connection refused" usually means MySQL is not running on your computer. On Windows, check that the MySQL service is started. On Mac or Linux, you may need to start it manually with a command like brew services start mysql or sudo systemctl start mysql.
If your connection works but queries are slow, the problem is usually a missing database index, not Flask itself. That is a database design question, not a connection question.
Frequently Asked Questions
Do I have to use Flask-SQLAlchemy or can I write raw SQL?
You can write raw SQL, and for very straightforward projects it is fine. But Flask-SQLAlchemy prevents SQL injection attacks, manages connections more safely, and saves you from writing repetitive code. Most teams use it from the start.
What is the difference between mysql-connector-python and PyMySQL?
Both drivers do the same job. mysql-connector-python is official and slightly more feature-complete. PyMySQL is lighter and faster for most use cases. For Flask projects, PyMySQL is more common because it works better with Flask-SQLAlchemy.
Can I connect to a MySQL database on a different computer?
Yes. Instead of localhost in your host setting, use the IP address or hostname of the computer where MySQL is running. Make sure that computer allows remote connections — by default, many MySQL installations only accept connections from the same machine.
What happens if the database connection drops while my app is running?
With raw connections, your app will crash. Flask-SQLAlchemy detects dropped connections and reconnects automatically, so your app keeps running. This is another reason to use Flask-SQLAlchemy in production.
Should I put my database password in my code?
Never. Store it in a separate config file that you do not commit to version control, or use environment variables. If your code goes to GitHub or anywhere public, anyone can see your password and access your database.