Connect MySQL using Python
Connect MySQL using Python, In this Blog post i will show how to connect a MySQL Database using Python Script.
Prior Diving into how to connect MySQL using Python , Make sure the below Software / Configuration are being installed & Setup into your workstation
- Python
- Shell or you can use the native Python Shell
- Command Prompt
- Xamp or Mamp with MySQL available
- A DataBase is created in MySQL if Not Check Out Here
- NotePad ++ or any Text Editor
Ok I assume now you have install all Software’s and done all Configuration above lets Get Started
Step 1
Install PyMysql library
(1) Open Command Prompt
(2) Locate where you install Python in your workstation
(3) Look For the Scripts File in your Python Folder
(4) Lets Install ….type the command “pip install pymysql”
(5) Wait ……….Installation to Finish
(6) After Installation Done , Open Python Terminal to Check Whether the Installation is being Installed Correctly
Type ” import pymysql ”
If the Command Return Nothing which means Installation was being done Correctly



Step 2
Write The Code to Connect Python To MySQL
Note: Remember Indentation
# Import the Library import pymysql.cursors # Connect to the database. try: # Connection Credentials connection = pymysql.connect(host='localhost', user='jane', password='jane', db='janedb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) # If Successful Connected Print Successful print ("connect successful!!") # If There Error throw an Error Message except pymysql.Error as e: print('Got error {!r}, errno is {}'.format(e, e.args[0])) # Close the connection connection.close()
Step 3
Run the Python Code
(1) Locate where you save the Python File
(2) type “.\yourPythonProjectName.py

I just Mess with the Password
Let See an Error Event Connected Unsuccessfully when i Mess with the database Password
- change database password from jane to jane1
