【python+unittest 接口自动化测试实战(二)】公共模块:pymysql 连接mysql数据库

# coding=utf-8
import pymysql


class MysqlUntil:
    def __init__(self, host, user, passwd, db, port, charset):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db
        self.port = int(port)
        self.charset = charset

    def conn_mysql(self):
        # 连接数据库
        try:
            conn = pymysql.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.db, port=self.port,
                                   charset=self.charset)
        except Exception:
            print("连接MYSQL失败")
        else:
            return conn

    def mysql_select(self, select_sql):
        # 执行查询语句,解析返回结果
        conn = self.conn_mysql()
        try:
            cur = conn.cursor()  # 获取一个游标
            cur.execute(select_sql)
            data = cur.fetchall()
            cols = cur.description
            cur.close()  # 关闭游标
            conn.close()  # 释放数据库资源
        except Exception as e:
            conn.rollback()
            print(e)
        else:
            col = []
            for i in cols:
                col.append(i[0])
            datas = list(map(list, data))
            data_list = []
            for data_one in datas:
                data_dict = {}
                for i in range(len(data_one)):
                    data_dict[col[i]] = data_one[i]
                data_list.append(data_dict)
            return data_list

    def mysql_insert(self, insert_sql):
        # 执行插入语句
        conn = self.conn_mysql()
        try:
            cur = conn.cursor()  # 获取一个游标
            sta = cur.execute(insert_sql)
            if sta == 1:
                print('DONE:' + insert_sql)
            else:
                print('FAIL')
            conn.commit()
            cur.close()  # 关闭游标
            conn.close()  # 释放数据库资源
        except Exception as e:
            conn.rollback()
            print(e)

你可能感兴趣的:(PYTHON,MYSQL,自动化测试,mysql,数据库,python)