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

11 篇文章 4 订阅
8 篇文章 1 订阅
# 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)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值