Therefore, this error indicates that the module required to connect to the database is missing from your system.
Let us explore the methods we can use to solve this error and get our application running.
What is MySQLDB?
MySQLDb is a free and open-source database interface connecting the MySQL server to a Python application. It provides low-level features that allow you to interact with your database in a near-native fashion.
What Causes the modulenotfounderror: no module named ‘mysqldb’ Error?
As mentioned, this error occurs when the module required to connect your Python application to the MySQL database is missing on your target system.
There are two leading causes:
- The module required is not installed
- Incorrect module for the target Python version.
Let us see how we can resolve this.
Solution – Install the MySQLDB Module
Before you can import and use the MySQLDB module on your application, you need to ensure it is installed on your system.
The following packages are required to use the MySQLDB interface:
mysql-python
mysqlclient
To install the above packages for Python3, run the commands:
$ sudo pip3 install mysql-python
$ sudo pip3 install mysqlclient
For Python 2, run the commands:
$ sudo pip install mysql-python
$ sudo pip install mysqlclient
You can also use conda package manager as provided in the commands below:
$ sudo conda install -c anaconda mysql-connector-python
You can verify its workings by importing the module as shown:
Solution 2 – Installing Visual C++ Build Tools
Sometimes, the MySQLDdb interface may fail to install due to missing Visual C++ build tools.
Open your browser and navigate to the resource below:
https://visualstudio.microsoft.com/visual-cpp-build-tools/
Download the Visual Studio installer and select the C++ Build Tools option or “Desktop Development with C++,” depending on the version.
Click on Install to process the required files.
Once completed, re-install the MySQLDB package with pip as shown in the previous commands.
Closing
This article discussed how to solve the modulenotfounderror: no module named ‘mysqldb’ error in Python.