概述
做过接口自动化的朋友都知道,接口自动化很重要的一个环节就是,结果对比。
结果对比又分很多种:
- 响应结果对比
- 入库对比
- redis对比
- 等…
今天就来讲讲怎么使用python连接数据,并执行sql查询数据,示例:mysql,clickhouse
函数封装
def local_db_execute(data):try:db = Api_db_config.objects.filter(id=data["db_id"]).values().first()# db是维护在数据库里的配置,通过db_id查询相关配置if db["db_type"] == 1:conn = pymysql.connect(host=db["db_host"],user=db["db_username"], passwd=db["db_password"],db=db["db_name"], port=int(db["db_port"]))cur = conn.cursor()cur.execute(f"SELECT * FROM {data['table_name']} where {data['where']} limit 1")result = [dict(zip([column[0] for column in cur.description], row)) for row in cur.fetchall()]return resultelif db["db_type"] == 2:# 建立连接,注意这里的参数赋值方式cur = Client(host=db["db_host"], port=int(db["db_port"]), user=db["db_username"],password=db["db_password"], database=db["db_name"])result = cur.execute(f"SELECT * FROM {data['table_name']} where {data['where']} limit 1")result_dict = [{column: value for column, value in zip(result.columns, result.fetchone())}]cur.disconnect()return result_dictexcept Exception as e:logger.info("数据库查询失败,原因:" + str(e))
# 返回的结果:
# { "表字段名": "字段值" }