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
- 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
![](https://i0.wp.com/miro.medium.com/max/1400/1*Xx7UEmFPklWd0uKyWjYfLA.png?w=640&ssl=1)
Then search for PYMYSQL and Click on install package
![](https://i0.wp.com/miro.medium.com/max/1400/1*5nyINECz9-VoNYa6uZLlxQ.png?w=640&ssl=1)
Step 2: Create a Database
Create a database called SELECTION_DB
using phpMyAdmin.
![](https://i0.wp.com/miro.medium.com/max/1400/1*TazA_wX5cg7NPlw5l-jPkA.png?w=640&ssl=1)
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.
![](https://i0.wp.com/miro.medium.com/max/1400/1*ocZW07S0ec3Umv7u05ZGHg.png?w=640&ssl=1)
That’s all folks.