I want to connect MySQLdb with Raspberry Pi. But when running my program, I get this error:

$ sudo python3 readMQ2sql.py
Traceback (most recent call last):
  File "readMQ2sql.py", line 17, in <module>
    import MySQLdb
ImportError: No module named 'MySQLdb'

You have to install the MySQLdb package:

sudo apt-get update


sudo apt-get install python3-dev libmysqlclient-dev

This took a while and finally:

sudo pip3 install mysqlclient

now it should work the following command:

pi@raspberrypi:~ $ python3.5
Python 3.5.2 (default, Dec 15 2017, 15:32:37)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
| improve this answer | |
  • modify 2nd command as (if any issues)-> sudo apt-get install python3-dev default-libmysqlclient-dev – djsreeraj Nov 11 '18 at 17:20

This 3 commands solved my issue with importing the module named 'MySQLdb'

sudo apt-get update

sudo apt-get install python3-dev **default-libmysqlclient-dev**

sudo pip3 install mysqlclient
| improve this answer | |

There is no MySQLdb for python3.x

PyMySQL is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and contains a pure-Python MySQL client library. The goal of PyMySQL is to be a drop-in replacement for MySQLdb.

How do I Install PyMySQL? Before proceeding further, you make sure you have PyMySQL installed on your machine. Just type the following in your Python script and execute it −


import pymysql

Install: pip install pymysql

Alternatively (e.g. if pip is not available), a tarball can be downloaded from GitHub and installed with Setuptools as follows −

$ # X.X is the desired pymysql version (e.g. 0.5 or 0.6).
$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python setup.py install
$ # The folder PyMySQL* can be safely removed now.

Example Following is an example of connecting with MySQL database "TESTDB" −


import pymysql

# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)

# disconnect from server
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.