Connect Python To MySQL Database With Pymysql And PhpMyAdmin.

Imran Sayed
3 min readNov 5, 2021

--

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.

Bonus info-

1. For Sequel Pro:

In case if you happen to use Sequel Pro Workbench, then your host and port will be different. e.g. host will be 127.0.0.1 and port will be 3306 , so you can connect like so. Please note that the below connection is for Sequel Pro, not PhpMyAdmin workbench.

connection = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="", database="SELECTION_DB")

2. Using mysql-connector-python module

Install mysql-connector-python instead of pymysql as explained above.
Please note this is a replacement of pymysql module. So you can use either.

import mysql.connector

database_connection = mysql.connector.connect(
host="localhost",
port=8889,
user="root",
password="root",
database="SELECTION_DB"
)

print(database_connection)

That’s all folks.

--

--

Imran Sayed
Imran Sayed

Written by Imran Sayed

👤 Full Stack Developer at rtCamp, Speaker, Blogger, YouTuber, Wordpress, React, Node, Laravel Developer http://youtube.com/ImranSayedDev

No responses yet