My favorite Python connector for MySQL or MariaDB is MySQLdb, the problem with this connector is that it is complicated to install on Windows!
I am creating this article for those who want to install MySQLdb for Python 3 for Windows. Especially me, since each time I am doing a Python project that needs to connect to MariaDB or MySQL I always look on how to install MySQLdb.
- Problems with installing MySQLdb on Windows
- Properly Installing MySQLdb on Windows
- Testing MySQLdb Installation
If you are interested why I prefer MySQLdb compared to other MySQL connectors you may want to read the comparison of MySQL-connector and MySQLdb from Charles Nagy.
You can actually install MySQLdb using pip. See pypi documentation here.
pip install MySQL-python
Unfortunately, the pypi documentation is already out of date with the latest release was on Jan 3, 2014.
You can still run the command above but it will look for Microsoft Visual C++ Build Tools, which if you install it in your Windows machine for the purpose of only using MySQLdb will become a program that occupies space but you will never ever use again.
So how do we install MySQLdb for Python on Windows? You can follow the steps below.
To install MySQLdb on Windows go to this link – https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
Download the appropriate .whl for your Python version.
I am currently using Python 3.6.8, so I downloaded
On windows command prompt, install the .whl file using pip. –
pip install [.whl filename]
In my case the command is
pip install mysqlclient-1.3.13-cp36-cp36m-win_amd64.whl
Note: The file on the command will be different if you use a different Python version or if there is an update on the version of the mysqlclient (MySQLdb).
Once pip says that you have Successfully installed mysqlclient you are good to go on using MySQLdb as your MySQL connector for Python.
Below is the code I use if my MySQLdb connector has been properly installed in Windows.
import MySQLdb print("Connecting to database using MySQLdb") db_connection = MySQLdb.connect(host='DB_HOST', db='DB_NAME', user='DB_USERNAME', passwd='DB_PASSWORD') print("Succesfully Connected to database using MySQLdb!") db_connection.close()
You can change the following parameters to check if it can connect to your MySQL database or MariaDB database.
If all is well, then when you run the code above it would print Succesfully Connected to database using MySQLdb!
If MySQLdb is not yet installed then it will raise a
<strong>ModuleNotFoundError</strong> like the screenshot below.
I hope this helped you install MySQLdb for Python on your Windows computer easier.
If there are any questions, errors or suggestions comment them down below so that I could check them out too.