python操作mysql数据库,一次性执行多条语句

背景:在构造测试场景的时候,往往会出现一次性要执行多条sql语句的情况,这时候为了避免每执行一条sql就连接一次数据库,可以加入 closeConn的参数,用以提高执行效率

1、前面的链接数据库,创建游标就不过多说明,下面直接放上代码:

    def __init__(self,dbName = None):
        self.currentConn = None
        self.host = "your host"
        self.user = "username"
        self.password = "password"
        self.dbName = dbName
        self.charset = "utf8mb4"
        self.resultlist = []

    def open(self):  # 创建连接
        try:
            conn = pymysql.connect(
                host = self.host,
                user = self.user,
                password = self.password,
                db = self.dbName,
                charset=self.charset,
            )
        except pymysql.err.OperationalError as e:
            logger.exception("数据库连接失败!")
            if "Errno 10060" in str(e) or "2003" in str(e):
                logger.error("数据库连接失败!")
            raise
        logger.info(f"数据库连接成功")
        self.currentConn = conn  # 数据库连接完成
        self.cursor = self.currentConn.cursor()  # 游标,用来执行数据库

    def close(self):  #关闭连接
        logger.info(f"关闭数据库连接")
        if self.cursor:
            self.cursor.close()
        self.currentConn.close()

2、虽然可以一次性传递多条语句,但是执行的时候,还是要逐条执行的

传递sql样例:"update t_sh set name = 'haha' where uid = '2200266416';update t_sh set name = 'aaa' where uid = '2200266416';select * from t_sh where uid = '2200266416';“
SQL拆分:

    def spliteSql(self,sql):
        sqllist = sql.split(';')
        return sqllist[0:-1]
        #最后面会多一条空值

3、执行,调用execSql时候,要手动指定closeConn = Flase

    def execSql(self,sql:str,closeConn = True) -> list:
        '''执行sql,支持执行多条sql语句。'''
        self.open()
        sqllist = self.spliteSql(sql)  #先处理传入的sql语句
        logger.info(f"开始执行sql语句")
        with self.cursor as my_cursor:
            for i in sqllist:
                my_cursor.execute(i)         #执行sql语句
                self.resultlist = my_cursor.fetchall()  #获取数据
                self.currentConn.commit()        #提交
        if self.currentConn:
            self.close()
        return self.resultlist

4、小结

1、使用这种方法,获取到的返回值总是最后一条命令的返回值,如果最后一条命令是update或者delete这种sql,则返回为()
2、sql的每一条语句后面都需要添加一个分号,不然最后splice时候 ,会少一条语句

完整代码:

#-*- coding:utf-8 -*-
"""
@author:yaren_zhou
@file: DButils.py
@time: 2019/12/06 14:56
@contact: [email protected]
@software: PyCharm
"""
import pymysql
import logging
logger = logging.getLogger(__name__)  #操作日志对象

class MysqlConn():
    '''
    数据库连接的公共类,提供连接数据库,查询,删除语句等操作
    '''

    def __init__(self,dbName = None):
        self.currentConn = None
        self.host = "your host"
        self.user = "username"
        self.password = "password"
        self.dbName = dbName
        self.charset = "utf8mb4"
        self.resultlist = []

    def open(self):
        try:
            conn = pymysql.connect(
                host = self.host,
                user = self.user,
                password = self.password,
                db = self.dbName,
                charset=self.charset,
            )
        except pymysql.err.OperationalError as e:
            logger.exception("数据库连接失败!")
            if "Errno 10060" in str(e) or "2003" in str(e):
                logger.error("数据库连接失败!")
            raise
        logger.info(f"数据库连接成功")
        self.currentConn = conn  # 数据库连接完成
        self.cursor = self.currentConn.cursor()  # 游标,用来执行数据库

    # 把多条sql拆分成单条,放进sqllist里面
    def spliteSql(self,sql):
        sqllist = sql.split(';')
        return sqllist[0:-1]
        #最后面会多一条空值

    def execSql(self,sql:str,closeConn = True) -> list:
        '''执行sql,支持执行多条sql语句。'''
        self.open()
        sqllist = self.spliteSql(sql)  #先处理传入的sql语句
        logger.info(f"开始执行sql语句")
        with self.cursor as my_cursor:
            for i in sqllist:
                my_cursor.execute(i)         #执行sql语句
                self.resultlist = my_cursor.fetchall()  #获取数据
                self.currentConn.commit()        #提交
        if self.currentConn:
            self.close()
        return self.resultlist

    # def execProc(self):

    def close(self):  #关闭连接
        logger.info(f"关闭数据库连接")
        if self.cursor:
            self.cursor.close()
        self.currentConn.close()

你可能感兴趣的:(python,测试,校招)