How to Solve "ModuleNotFoundError: No module named 'mysql'" in Python
The ModuleNotFoundError: No module named 'mysql'
error in Python indicates that you're trying to use the mysql-connector-python
library (or a similarly named library) without it being installed in your current Python environment, or it can happen if the environment is not active, or not correctly configured in your IDE.
This guide explains how to install the correct library and troubleshoot common installation problems.
Understanding the Error
Unlike some other database connectors (like psycopg2
for PostgreSQL), the mysql
package itself doesn't contain the necessary drivers to connect to a MySQL database. You need to install a specific connector package. The official and recommended package is mysql-connector-python
.
The ModuleNotFoundError
means that the mysql
package (or, more accurately, a package you think provides the MySQL connection functionality) is either:
- Not installed at all.
- Installed in a different Python environment than the one your code is currently using.
- Installed, but the code is using the wrong import statement.
Installing mysql-connector-python
(The Correct Package)
The correct package to install for MySQL support in Python is mysql-connector-python
. Do not install a package simply called mysql
, as it is not the correct one. Install it using pip
:
pip install mysql-connector-python
- Multiple Python Versions: If you have multiple Python versions, use
pip3
(or a more specific version likepip3.9
orpip3.10
) to ensure you're installing to the right environment. Or, better yet, usepython -m pip
(orpython3 -m pip
, orpy -m pip
on Windows):python -m pip install mysql-connector-python # Use the current Python
python3 -m pip install mysql-connector-python # Use Python 3 - Permissions Errors: If you get a permissions error, try:
sudo pip3 install mysql-connector-python # Linux/macOS (Use with caution)
pip install mysql-connector-python --user # Install for the current user- Using virtual environments (explained below) avoids permission issues and is highly recommended.
- Conda: If you use Anaconda:
conda install -c anaconda mysql-connector-python
Verifying the Installation
After installing, verify the installation with a simple Python script:
import mysql.connector
print(mysql.connector.__version__) # Verify successful import and version
If this script runs without errors and prints the version, the installation was successful. If you still get a ModuleNotFoundError
, proceed to the troubleshooting steps.
Troubleshooting ModuleNotFoundError
Virtual Environments (Crucial!)
Always use virtual environments to isolate your project's dependencies. This is the single most important step to avoid conflicts and ensure reproducibility.
-
Create (if you don't have one):
python3 -m venv venv # Or python -m venv venv, or py -m venv venv
-
Activate:
-
Linux/macOS:
source venv/bin/activate
-
Windows (cmd.exe):
venv\Scripts\activate.bat
-
Windows (PowerShell):
venv\Scripts\Activate.ps1
If you see an error stating that
.ps1
can not be loaded, run the following command:Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
-
-
Install:
pip install mysql-connector-python
(inside the activated environment).
Your terminal prompt should change (e.g., (venv) $
). This confirms the environment is active.
Multiple Python Versions
You might have installed mysql-connector-python
for a different Python version than the one your script is using.
- Check Python Version:
python --version
(orpython3 --version
) - Use Correct
pip
: Ensure you use thepip
(orpip3
,pip3.x
,python -m pip
) that matches the Python version you intend to use.
IDE Configuration (VS Code, PyCharm)
Your IDE (VS Code, PyCharm, etc.) must be configured to use the correct Python interpreter and virtual environment.
-
VS Code:
- Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P).
- Type "Python: Select Interpreter".
- Choose the interpreter for your virtual environment.
-
PyCharm:
- Go to "File" -> "Settings" (or "PyCharm" -> "Preferences" on macOS) -> "Project" -> "Python Interpreter".
- Select/add the correct interpreter.
Jupyter Notebook
In Jupyter Notebook, use !pip install mysql-connector-python
within a cell. However, this installs into the environment Jupyter itself is running in, which might not be your project's environment. Ensure your Jupyter kernel uses the correct environment.
Naming Conflicts
Never name your own Python files or directories mysql.py
or mysql
(or the name of any other module you're using). This creates a naming conflict, and Python will try to import your file instead of the installed library.
Reinstalling the Package
As a last resort, uninstall and reinstall:
pip uninstall mysql-connector-python
pip install mysql-connector-python
Example Code (Connecting to MySQL)
Here's a basic example of connecting to a MySQL database (remember to replace the placeholders with your actual credentials):
import mysql.connector
# Replace with your actual connection details
try:
cnx = mysql.connector.connect(
host="127.0.0.1", # Or your MySQL server address
port=3306, # Default MySQL port
user="your_username",
password="your_password",
database="your_database" # Specify the database
)
cur = cnx.cursor() # Create a cursor object
cur.execute("SELECT CURDATE()") # Execute a query
row = cur.fetchone() # Fetch the result
print("Current date is:", row[0]) # Print the date
cnx.close() # Close the connection
except mysql.connector.Error as err:
print(f"Something went wrong: {err}")
- Replace
"127.0.0.1"
,3306
,"your_username"
,"your_password"
, and"your_database"
with your actual MySQL server details. - This example connects, executes a simple query (
SELECT CURDATE()
), fetches the result, prints it, and closes the connection. - The
try/except
is used to handle errors when establishing the connection.
Conclusion
The ModuleNotFoundError: No module named 'mysql'
error (when you intend to use mysql-connector-python
) is almost always a problem with your Python environment.
- By correctly installing
mysql-connector-python
usingpip
within a virtual environment and configuring your IDE to use that environment, you can resolve this issue. - Always double-check that you are using the correct
pip
associated with your intended Python version, and avoid naming conflicts with your own files.
This will get you connected to your MySQL database.