MySQL MariaDB

modulenotfounderror: no module named ‘mysqldb’

The modulenotfounderror: no module named ‘mysqldb’ error occurs when running a Python script that interacts with the MySQL database.Before you can connect your Python application to a MySQL database, you will install a connecting interface for the database.

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:

  1. The module required is not installed
  2. 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-connector-python

mysql-python

mysqlclient

To install the above packages for Python3, run the commands:

$ sudo pip3 install mysql-connector-python

$ sudo pip3 install mysql-python

$ sudo pip3 install mysqlclient

For Python 2, run the commands:

$ sudo pip install mysql-connector-python

$ 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-python

$ sudo conda install -c anaconda mysql-connector-python

You can verify its workings by importing the module as shown:

import MySQLdb

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list