Connecting MySQL Database in Python using PyMySQL

1- What is PyMySQL?

In order to connect Python to a database you need a driver, which is a library used to Interact with the database. For MySQL database, you have such 3 Driver choices:
  1. MySQL/connector for Python
  2. MySQLdb
  3. PyMySQL
Driver Discription
MySQL/Connector for Python This is a library provided by the MySQL community.
MySQLdb MySQLdb is a library that connects to MySQL from Python, it is written in C language and it is free and open source software.
PyMySQL This is a library that connects to MySQL from Python and it is a pure Python library. PyMySQL's goal is to replace MySQLdb and work on CPython, PyPy and IronPython.
PyMySQL is an open source project, and you can see its source code here:

2- Install PyMySQL

In order to install PyMySQL on Windows (or Ubuntu/Linux) you need to open the CMD window, and run the following statement:

pip install PyMySQL

3- Sample Database

"Simplehr" is a sample database used in many tutorials on o7planning. In the post, I also use it. You can create the database based on the guide below:

4- Connect MySQL from Python with PyMySQL

The following simple example uses Python to connect to MySQL and query the Department table:
connectExample.py
import pymysql.cursors 


# Connect to the database
connection = pymysql.connect(host='192.168.5.134',
                             user='root',
                             password='1234',                            
                             db='simplehr',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

print ("connect successful!!")

try:
 

    with connection.cursor() as cursor:
        # SQL
        sql = "SELECT Dept_No, Dept_Name FROM Department "
       
        # Execute query
        cursor.execute(sql)
       
        print ("cursor.description: ", cursor.description)

        print()

        for row in cursor:
            print(row)
           
finally:
    connection.close()
Results of the example:

Utility Module:

The advice here is that you should create a utility module to connect to the database. In case I create a module named as "myconnutils", which defines the getConnection() function to returns a connection.
myconnutils.py
import pymysql.cursors 

# Function return a connection
def getConnection():
   
    # You can change the connection arguments.
    connection = pymysql.connect(host='192.168.5.134',
                                 user='root',
                                 password='1234',                            
                                 db='simplehr',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    return connection

 

5- Query Example

The following example queries the Employee table, Python uses %s as a "placeholder" for the parameter, which is independent of the parameter type. For example:

sql1 = "Insert into Department (Dept_Id, Dept_No, Dept_Name) values (%s, %s, %s) "

sql2 = "Select * from Employee Where Dept_Id = %s "
queryExample.py
# Use your utility module.
import myconnutils


connection = myconnutils.getConnection()

print ("Connect successful!")

sql = "Select Emp_No, Emp_Name, Hire_Date from Employee Where Dept_Id = %s "

try :
    cursor = connection.cursor()

    # Execute sql, and pass 1 parameter.
    cursor.execute(sql, ( 10 ) ) 
    
    print ("cursor.description: ", cursor.description)
    
    print()
    
    for row in cursor:
        print (" ----------- ")
        print("Row: ", row)
        print ("Emp_No: ", row["Emp_No"])
        print ("Emp_Name: ", row["Emp_Name"])
        print ("Hire_Date: ", row["Hire_Date"] , type(row["Hire_Date"]) )

finally:
    # Close connection.
    connection.close()    
  

6- Insert Example

insertExample.py
# Use your utility module.
import myconnutils
import pymysql.cursors


connection = myconnutils.getConnection()

print ("Connect successful!")

try :
    cursor = connection.cursor()
  
    sql = "Select max(Grade) as Max_Grade from Salary_Grade "
    cursor.execute(sql)
  
    # 1 row.
    oneRow = cursor.fetchone()
    
    # Output: {'Max_Grade': 4} or {'Max_Grade': None}
    print ("Row Result: ", oneRow)
  
    grade = 1
  
    if oneRow != None and oneRow["Max_Grade"] != None:
        grade = oneRow["Max_Grade"] + 1
  
    cursor = connection.cursor()
  
  
    sql =  "Insert into Salary_Grade (Grade, High_Salary, Low_Salary) " \
         + " values (%s, %s, %s) "
  
    print ("Insert Grade: ", grade)
  
    # Execute sql, and pass 3 parameters.
    cursor.execute(sql, (grade, 2000, 1000 ) )
  
    connection.commit()

finally:
    # Close connection.
    connection.close()      

7- Update Example

updateExample.py
# Use your utility module.
import myconnutils
import pymysql.cursors
import datetime


connection = myconnutils.getConnection()

print ("Connect successful!")

try :
    cursor = connection.cursor()
   
    sql = "Update Employee set Salary = %s, Hire_Date = %s where Emp_Id = %s " 
   
    # Hire_Date
    newHireDate = datetime.date(2002, 10, 11)
   
    # Execute sql, and pass 3 parameters.
    rowCount = cursor.execute(sql, (850, newHireDate, 7369 ) )
   
    connection.commit()
   
   
    print ("Updated! ", rowCount, " rows")

finally:
    # Close connection.
    connection.close()       

8- Delete Example

deleteExample.py
# Use your utility module.
import myconnutils

connection = myconnutils.getConnection()

print ("Connect successful!")



try :
    cursor = connection.cursor()
   
    sql = "Delete from Salary_Grade where Grade = %s" 
   
  
    # Execute sql, and pass 1 parameters.
    rowCount = cursor.execute(sql, ( 3 ) )
   
    connection.commit()
   
   
    print ("Deleted! ", rowCount, " rows")

finally:
    # Close connection.
    connection.close()