How to connect to MySQL db from python 3 on 16.04

You need python development libraries to build python modules:

sudo apt install python3-dev libpython3-dev

should take care of that for you.

But the recommended way to add this in Ubuntu would be to use the Ubuntu repositories. Thus, to install mysql bindings for python3, run

sudo apt install python3-mysqldb

This will install the bindings needed to connect to mysql from Python 3, and ensures that it will be upgraded along with other packages of your system. This is recommended, unless you specifically need a newer version, or the package is not available in the Ubuntu repositories.


MySQLdb doesn't work with Python 3. if possible for you to switch from MySQLdb then I recommend you to use MySQL connector Python. Because it works with both Python 2 and 3 and it is official Oracle driver of MySQL for working with Python.

pip install mysql-connector-python

if pip fails you can download the installer from https://dev.mysql.com/downloads/connector/python/

i.e. installing MySQL Connector using DEB package Refer this guide to download and install

This module adheres to Python Database API Specification v2.0 (PEP 249).

Then Use connect() method of mysql connector python to connect to MySQL.pass the required argument to connect() method. i.e. Host, username, password, and database name