Python and MySQL Error: No module named mysql

Learn how to fix the ImportError: No module named mysql in Python scripts

Posted on October 18, 2021

When you run a .py script from the command line, you may encounter a Python ImportError statement as shown below:

$ python
Traceback (most recent call last):
  File "", line 1, in <module>
    import mysql.connector
ImportError: No module named mysql

The error above is because the Python compiler can’t find a package named mysql in your Python libraries.

To install the mysql module, you need to install the mysql-connector-python package using pip as follows:

pip install mysql-connector-python

You can also install the MySQL Connector/Python library through other distributions as listed here.

Once the installation is finished, try to run the script with the python command again. It should work this time.

Sometimes, you may also encounter a new error saying invalid syntax as follows:

Traceback (most recent call last):
  File "", line 1, in <module>
    import mysql.connector
    f"This connection is using {tls_version} which is now "
SyntaxError: invalid syntax

The error above is because MySQL Connector/Python library has dropped the support for Python 2 in version 8.0.23. You can see v8.0.23 changelog for more information.

If you’re using Python 2, then the latest version of MySQL Connector/Python library that you can use is version 8.0.22.

You need to uninstall the current library and then install the exact version using pip as shown below:

pip uninstall mysql-connector-python
pip install mysql-connector-python==8.0.22

Now the library should be able to run both in Python 2 or Python 3 environment.

You’ve just learned how to fix the No module named mysql error in Python. Nice work! 👍

Related articles:

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.