1.连接数据库查询数据
安装mysql驱动,导入模块不报错就行
pip install -i https://pypi.douban.com/simple/ mysqlclient
# -*- coding: utf-8 -*- # @Author: jiujiu # @Date: 2020-03-12 14:39:11 # @Last Modified time: 2020-03-12 14:51:48 import MySQLdb conn = MySQLdb.connect( host='10.2.40.217', port=3306, user='root', passwd='123456', db='zc-car-info-manage', charset='utf8' ) cur = conn.cursor() #创建一个游标对象 cur.execute("select * from t_sys_user ") #执行SQL语句,注意这里不返回结果,只是执行而已 print(cur.fetchall())#fetchall方法返回所有匹配的元组,给出一个大元组(每个元素还是一个元组);fetchone()只给出一条数据
执行结果
2.获取数据库数据重构及数据转换
# -*- coding: utf-8 -*- # @Author: jiujiu # @Date: 2020-03-12 14:39:11 # @Last Modified time: 2020-03-12 15:26:35 import MySQLdb.cursors import json class operation_db: """docstring for operation_db""" def __init__(self): self.conn = MySQLdb.connect( host='10.2.40.217', port=3306, user='root', passwd='123456', db='zc-car-info-manage', charset='utf8', cursorclass=MySQLdb.cursors.DictCursor #把表的列名显示出来 ) self.cur = self.conn.cursor() #创建一个游标对象 #查询一条数据 def search_one(self,sql): self.cur.execute(sql) #执行SQL语句,注意这里不返回结果,只是执行而已 result = self.cur.fetchone()#fetchall方法返回所有匹配的元组,给出一个大元组(每个元素还是一个元组);fetchone()只给出一条数据 result = json.dumps(result)#以json格式展示 print(result) return result if __name__ == '__main__': op_mysql = operation_db() res = op_mysql.search_one("select * from t_sys_user") print(type(res))#输出返回值的类型,是字符串格式
运行结果:
3.返回数据和数据库数据进行对比
#通过sql获取预期结果 def get_expect_data_for_mysql(self,row): op_mysql = operation_db() sql = self.get_expect_data(row) res = op_mysql.search_one(sql) return res.decode('unicode-escape')
def is_equal_dict(self,dict_one,dict_two): ''' 判断2个字典''' if isinstance(dict_one,str): dict_one = json.loads(dict_one) if isinstance(dict_two,str): dict_two = json.loads(dict_two) return cmp(dict_one,dict_two)
if self.com_util.is_equal_dict(expect,res) == 0:#判断,需去掉结果的格式化 self.data.write_result(i,'pass') pass_count.append(i) else: self.data.write_result(i,res) fail_count.append(i)