Python Connect To MySQL Database Example

When you want to connect to MySQL database in Python code, you can use PyMySQLPyMySQL is a third party library which provide classes for you to get MySQL database connection, execute insert, delete, update, select sql command. It also support transaction management. This article will show you an example about how to use PyMySQL to operate on MySQL database table.

1. Install PyMySQL.

Before you can use PyMySQL, you should install it first. You can use pip to install like below.

$ pip3 install PyMySQL

You can run pip3 show command to verify PyMySQL installation.

$ pip3 show PyMySQL

2. Use PyMySQL To Connect And Operate MySQL Database.

Below is the steps that you use PyMySQL library in Python code.

  1. Import pymysql connect, cursors class.
    from pymysql import connect, cursors
  2. Call connect method to get MySQL database connection object.
    conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
  3. Get database cursor object by connection object’s cursor() function.
    conn.cursor() as cursor:
  4. Execute sql statement use the cursor object.
    cursor.execute(sql)
  5. If the sql statement is a select statement, then call cursor object’s fetchall() or fetchone() method to get the sql execution result. Please note after invoke fetchall(), the cursor will move to the last row of the result, so if you call fetchall() method again, there will have no row returned.
    row = cursor.fetchall()
    
    or
    
    row = cursor.fetchone()
  6. If the sql statement is a insert, update, delete statement, then call connection object’s commit() function to commit the changes to MySQL database to take effect.
    conn.commit()
  7. Do not forget to close the MySQL database connection object at the end to release database resources.
    if conn is not None:
            conn.close()
            conn = None

3. PyMySQL Operate MySQL Database Example.

In this example, the MySQL database name is dev2qa_example, the table name is user_account. The table has four columns that are id, user_name, password and email. The id column is auto incremented.

READ :   How To Assign Variables To Child Template Use {% include %} Tag In Django

mysql table user_account structure

The python source code contain methods to insert, update, delete and select user account data.

'''
Created on Jan 26, 2019

@author: zhaosong
'''

from pymysql import connect, cursors

global_host='127.0.0.1'
global_user='jerry'
global_password='jerry'
global_db='dev2qa_example'
global_charset='utf8'
global_cursorclass=cursors.DictCursor

# get mysql connection object.
def open_mysql_connection(host='127.0.0.1', user='jerry', password='jerry', db='dev2qa_example', charset='utf8', cursorclass=cursors.DictCursor):
    conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
    return conn
    
# close mysql connection.    
def close_mysql_connection(conn):
    if conn is not None:
        conn.close()
        conn = None

# execute insert, update or delete sql command.
def execute_insert_update_delete_sql(sql, host, user, password, db, charset, cursorclass):
    execute_row_count = 0
    conn = None
    print('sql = ' + sql)
    try:
        if string_is_not_empty(sql):
            conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
            with conn.cursor() as cursor:
                execute_row_count = cursor.execute(sql)
    except Exception as ex:
        print(ex)
    finally:
        if conn is not None:
            conn.commit()
            close_mysql_connection(conn)
        return execute_row_count    
 
# execute select sql command.                    
def execute_select_sql(sql, host, user, password, db, charset, cursorclass):
    ret = list()
    conn = None
    print('sql = ' + sql)
    try:
        if string_is_not_empty(sql):
            conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
            with conn.cursor() as cursor:
                row_count = cursor.execute(sql)
                print('select return row count = ' + str(row_count))
                row = cursor.fetchall()
                print(row)
                ret.append(row)
    except Exception as ex:
        print(ex)            
    finally:
        if conn is not None:
            close_mysql_connection(conn)
        return ret        

# insert user account to database table dev2qa_example.user_account.                
def insert_user_account(user_name, password, email):
    print('**********Begin insert_user_account.**********')
    
    if string_is_not_empty(user_name) and string_is_not_empty(password) and string_is_not_empty(email):
        # first check whether user account exist or not.
        sql = "select count(id) as count from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
        row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        
        account_exist = False
        for row in row_list:
            for column in row:
                exist_count_number = column.get('count')
                if exist_count_number > 0:
                    account_exist = True
        
        if not account_exist:
            print('User ' + user_name + ' do not exist in database. Insert the user account to database table.')
            sql = "insert into user_account(user_name, password, email) values('"+user_name+"','"+password+"','"+email+"')"
            insert_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
            print('Insert ' + str(insert_row_count) + ' row data successfully.')
        else:
            print('User account exist, can not insert.')    
    else:
        print('user_name, password, email can not be empty.')        
        
    print('**********End insert_user_account.**********')    
   
# update user account data.            
def update_user_account(user_name, password, email):
    print('**********Begin update_user_account.**********')
    
    if string_is_not_empty(user_name):
        sql = "update dev2qa_example.user_account set password = '" + password + "', email = '" + email + "' where lower(user_name) = '" + user_name.lower() + "'"
        update_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
    
        if update_row_count == 0:
            print('User account do not exist, insert it now.')
            insert_user_account(user_name, password, email)
        else:
            print('Update ' + str(update_row_count) + ' row data successfully.')
    else:
        print('user_name can not be empty.')        
           
    print('**********End update_user_account.**********')
    
# delete user account data from database table.    
def delete_user_account(user_name):
    print('**********Begin delete_user_account.**********')
    
    if string_is_not_empty(user_name):
        sql = "delete from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower()+"'"
        delete_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        print('Delete ' + str(delete_row_count) + ' row data successfully.')
        
    print('**********End delete_user_account.**********')
    
# execute select sql command to get user account data by user_name.    
def get_user_account_by_user_name(user_name):
    print('**********Begin get_user_account_by_user_name.**********')
    sql = "select * from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
    row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
    print('**********End get_user_account_by_user_name.**********')

# check whether the string is empty or not.
def string_is_not_empty(str):
    if str is None:
        return False
    elif len(str.strip()) == 0:
        return False
    else:
        return True

if __name__ == '__main__':
    # first delete user account jerry.
    delete_user_account('jerry')
    
    # then insert a user account jerry into database.
    insert_user_account('jerry', 'jerry', '[email protected]')
    # show user account data to verify the insert action.
    get_user_account_by_user_name('jerry')
    
    # update usr account information.
    update_user_account('jerry', 'jerry888', '[email protected]')
    # check the updated user account info again.
    get_user_account_by_user_name('jerry')

Below is above code execution result.

**********Begin delete_user_account.**********
sql = delete from dev2qa_example.user_account where lower(user_name) = 'jerry'
Delete 1 row data successfully.
**********End delete_user_account.**********
**********Begin insert_user_account.**********
sql = select count(id) as count from dev2qa_example.user_account where lower(user_name) = 'jerry'
select return row count = 1
[{'count': 0}]
User jerry do not exist in database. Insert the user account to database table.
sql = insert into user_account(user_name, password, email) values('jerry','jerry','[email protected]')
Insert 1 row data successfully.
**********End insert_user_account.**********
**********Begin get_user_account_by_user_name.**********
sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
select return row count = 1
[{'id': 42, 'user_name': 'jerry', 'password': 'jerry', 'email': '[email protected]'}]
**********End get_user_account_by_user_name.**********
**********Begin update_user_account.**********
sql = update dev2qa_example.user_account set password = 'jerry888', email = '[email protected]' where lower(user_name) = 'jerry'
Update 1 row data successfully.
**********End update_user_account.**********
**********Begin get_user_account_by_user_name.**********
sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
select return row count = 1
[{'id': 42, 'user_name': 'jerry', 'password': 'jerry888', 'email': '[email protected]'}]
**********End get_user_account_by_user_name.**********

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.