PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb
话不多说,直接上代码来说明用途

#!/user/bin/env python
#coding=utf-8

from pymysql import connect,cursors
from pymysql.err import OperationalError
import os
import configparser as cparser
from builtins import int
from framework.logger import Logger
import time

'''
========读取config.ini文件中mysql配置========
'''
base_dir = str(os.path.dirname(os.path.dirname(file)))
file_path = base_dir + "\config\config.ini"

cf = configUtil(file_path)
host = cf.get("sitmysqlconf", "host")
port = cf.get("sitmysqlconf", 'port')
db = cf.get("sitmysqlconf", 'db_name')
user = cf.get("sitmysqlconf", 'user')
password = cf.get("sitmysqlconf", 'password')

logger = Logger(logger="mysqlUtils").getlog()

'''
===========封装MySQL基本操作=============
'''
class mysqlUtils:

def __init__(self):
    '''
    初始化获得mysql连接
    '''
    try:
        self.conn = connect(host=host,
                            port=int(port),
                            user=user,
                            password=password,
                            db=db,
                            charset='utf8mb4',
                            cursorclass=cursors.DictCursor
                            )
    except OperationalError as e:
        print (e)

def cursor(self):
    '''
    获得游标
    '''
    self.conn.cursor()

def getDict(self,tableName,systemID,ColumnNameKey,ColumnNameValue):
    '''
    公共方法,获取id的字典
    '''
    with self.conn.cursor() as cursor:
        cursor.execute("select *  from %s WHERE system_id = %s and %s = %s",(tableName,systemID,ColumnNameKey,ColumnNameValue))
    Dict = cursor.fetchone()
    self.conn.commit()
    return Dict

    def AttentionLibraryDelete(self,system_id,merchant_id):
    '''非正常删除数据,即直接操作数据库删除'''
    with self.conn.cursor() as cursor:
        cursor.execute("delete  from tableName where system_id = %s and merchant_id = %s;",(system_id,merchant_id))
    self.conn.commit()

      def addMerchantTOIT(self,merchant_id):
    '''把商家关联到XXX行业中'''
    #realSQL = "INSERT INTO tableName (system_id, merchant_id, business_id, status, creator_id, create_date, updater_id, update_date) VALUES ('7b6a99f3bce14915863cde5104bdf2c3', %s, '11', 'A', '8', unix_timestamp(now())*1000, '8', unix_timestamp(now())*1000);"  % repr(merchant_id)
    with self.conn.cursor() as cursor:
        cursor.execute("INSERT INTO t_sys_merchant_business (system_id, merchant_id, business_id, status, creator_id, create_date, updater_id, update_date) VALUES ('7b6a99f3bce14915863cde5104bdf2c3', %s, '11', 'A', '8', unix_timestamp(now())*1000, '8', unix_timestamp(now())*1000);",(merchant_id))
    self.conn.commit()
    logger.info('把商家【%s】关联到xxx成功'%merchant_id)

def close(self):
'''
关闭mysql数据库
'''
self.conn.close()