Connect Python To MySQL Database With Pymysql And PhpMyAdmin.

If we already have a PhpMyAdmin workbench, we can not only connect PHP but also Python to a MySql Database. In this blog, we are going to use the following tools and packages.

  • PyCharm — A Python IDE
  • MAMP — A local development environment. ( You can also use XAMP )
  • PhpMyAdmin — MySQL Workbench.
  • Pymysql module — A Python MySQL client library

Let’s assume you have already installed and set up PyCharm, MAMP with PhyMyAdmin.

Step One: Install pymysql

You can install it in two ways

  1. Through Terminal — by running the following command in the terminal of your PyCharm IDE.
pip install pymysql

2. Through PYCharm, you can also go to Preferences > Python Interpreter > Click on the + button

Then search for PYMYSQL and Click on install package

Step 2: Create a Database

Create a database called SELECTION_DB using phpMyAdmin.

Step 3: Connect to Database using pymysql

Create a file called example.py and add the below code. Notice the port number in the above PHPMyAdmin picture is 8889 and the host is localhost . That’s what we have put in the parameters below.

import pymysql

# database connection
connection = pymysql.connect(host="localhost", port=8889, user="root", passwd="root", database="SELECTION_DB")cursor = connection.cursor()
# some other statements  with the help of cursor
connection.close()

Click on the run button, to run the python file. As you can see in the terminal, it’s successfully connected.

That’s all folks.

Leave a Reply