NB! A more recent update to this tutorial has been published for installing the MySQL connector package in Python 2021.
Installing the MySQL connector package for Python can sometimes be a bit more of a struggle than it should be. There are two separate versions of the MySQL connector package that are used for either Python 2 or 3, you'll need to download the correct package using pip as well as some necessary dependencies in order to use it on your version.
Installing MySQL for Python 2
If you are using Python 2.x, the package you'll need is called MySQL-python. For this you will need to install the following
dependencies
first:
sudo apt-get install build-essential python-dev libmysqlclient-dev
Before installing this package make sure you have
pip installed
for the correct version of Python. This can be achieved by including your version number within the package name.
sudo apt-get install python2-pip
Next you can
install the MySQL connector
using pip:
sudo pip2 install MySQL-python
If this did not work for any reason you can also attempt to
install it directly from the repository
as "python-mysqldb" instead of using pip.
sudo apt-get install python-mysqldb
Once it is installed you can
import
it into your Python script like so:
import MySQLdb
Installing MySQL for Python 3
If you are using Python 2.x, the package you'll need is called mysql-connector. For this you will need to install the following
dependencies
first:
sudo apt-get install build-essential python3-dev libmysqlclient-dev
Before installing this package make sure you have
pip installed
for the correct version of Python. This can be achieved by including your version number within the package name.
sudo apt-get install python3-pip
Next you can
install the MySQL connector
using pip:
sudo pip3 install mysql-connector
If this did not work for any reason you can also attempt to
install itdirectly from the repository
as "python3-mysql.connector" instead of using pip.
sudo apt-get install python3-mysql.connector
Once it is installed you can
import
it into your Python script like so:
import MySQLdb
Installing MySQL for Python can be quite a pain sometimes and there are often unforeseen errors that occur. If you are still getting errors when trying to install the package or Python is not recognizing the import,
leave a comment below for some help
.