4

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'
Aurora0001
  • 6,357
  • 3
  • 25
  • 39

4 Answers4

6

You have to install the MySQLdb package:

sudo apt-get update

then

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
>>>
bierschi
  • 340
  • 1
  • 2
  • 7
1

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
djsreeraj
  • 111
  • 3
0

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 −

#!/usr/bin/python3

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" −

#!/usr/bin/python3

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
db.close()
goldilocks
  • 60,325
  • 17
  • 117
  • 234
0

Tried djsreeraj's suggestion, which is outdated. (Perhaps for Bullseye?) Took the option suggested: -

sudo apt-get install python3-dev libmariadb-dev

All working fine, with sudo pip3 install mysqlclient having been run previously.

Richard
  • 21
  • 5