To resolve the ModuleNotFoundError: No module named 'mysql' error, follow these steps:
1. Identify the Right MySQL Module
There are several MySQL connector modules available for Python. The most common ones are:
mysql-connector-python (official MySQL connector)
PyMySQL (pure Python MySQL client)
2. Install the MySQL Module
You can install the required module using pip. Open your terminal or command prompt and run one of the following commands:
For mysql-connector-python:
pip install mysql-connector-python
For PyMySQL:
pip install pymysql
3. Verify the Installation
After installation, verify it by running a simple script to import the module:
# For mysql-connector-pythonimport mysql.connector# For PyMySQLimport pymysql
If there are no errors, the module is installed correctly.
4. Using the MySQL Module
Here are basic examples of how to use each module to connect to a MySQL database.
Example with mysql-connector-python:
import mysql.connector# Establish the connectionconn = mysql.connector.connect( host="your_host", user="your_username", password="your_password", database="your_database")# Create a cursor objectcursor = conn.cursor()# Execute a querycursor.execute("SELECT * FROM your_table")# Fetch the resultsresults = cursor.fetchall()# Print the resultsfor row in results: print(row)# Close the connectionconn.close()
Example with PyMySQL:
import pymysql# Establish the connectionconn = pymysql.connect( host="your_host", user="your_username", password="your_password", database="your_database")# Create a cursor objectcursor = conn.cursor()# Execute a querycursor.execute("SELECT * FROM your_table")# Fetch the resultsresults = cursor.fetchall()# Print the resultsfor row in results: print(row)# Close the connectionconn.close()
Troubleshooting
If you still encounter issues:
- Ensure the package is installed in the correct environment: If you are using a virtual environment, make sure to install the package with the environment activated.
- Check Python version compatibility: Ensure the MySQL module you are installing is compatible with your Python version.
- Check for typos: Ensure you are using the correct module name in your import statements.
By following these steps, you should be able to resolve the ModuleNotFoundError: No module named 'mysql' error.