unittest(22)- p2p项目实战(7)-do_mysql

# 7. do_msql.py

import mysql.connector
from p2p_project_2020_1_21.tools import project_path
from p2p_project_2020_1_21.tools.read_config import ReadConfig


class DoMysql:

    def do_mysql(self, query_sql, state="all"):  # 查询语句参数化, 通过state控制返回的结果是1条或者多条记录
        # 从配置文件读取db_config
        db_config = eval(ReadConfig().get_config(project_path.case_config_path, "DB", "db_config"))
        # 创建一个数据库连接
        cnn = mysql.connector.connect(**db_config)  # 传入的参数是字典时,要使用关键字参数的形式
        # 游标cursor
        cursor = cnn.cursor()
        # 执行查询语句
        cursor.execute(query_sql)
        # 获取结果,打印结果
        if state == 1:
            res = cursor.fetchone()  # 返回的数据是元组,结果只有1条记录
        else:
            res = cursor.fetchall()  # 返回的结果是列表类型,列表嵌套元组,可以是多行记录,也可以是一行记录
        # print(res)
        # 操作完数据库后一定要记得关闭
        # 关闭游标
        cursor.close()
        # 关闭连接
        cnn.close()
        return res


if __name__ == '__main__':
    query_sql = "select * from student1 where id < 4"
    res = DoMysql().do_mysql(query_sql)
    print(res)
    print(res[0][0])

配置文件如图:

猜你喜欢

转载自www.cnblogs.com/come202011/p/12232218.html
P2P
今日推荐