Django+vue自动化测试平台(26)-- 接口自动化测试之连接数据库执行sql

概述

做过接口自动化的朋友都知道,接口自动化很重要的一个环节就是,结果对比。

结果对比又分很多种:

  • 响应结果对比
  • 入库对比
  • redis对比
  • 等...

今天就来讲讲怎么使用python连接数据,并执行sql查询数据,示例:mysql,clickhouse

函数封装

python 复制代码
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 result
        elif 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_dict

    except Exception as e:
        logger.info("数据库查询失败,原因:" + str(e))
# 返回的结果:
# { "表字段名": "字段值" }
相关推荐
老华带你飞18 分钟前
建筑材料管理|基于springboot 建筑材料管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
weixin_3077791328 分钟前
Jenkins Pipeline 完全指南:核心概念、使用详解与最佳实践
开发语言·ci/cd·自动化·jenkins·etl
半山烟雨半山青1 小时前
微信内容emoji表情包编辑器 + vue3 + ts + WrchatEmogi Editor
前端·javascript·vue.js
NaiLuo_451 小时前
MySQL基本查询
数据库·mysql
刺客xs1 小时前
MYSQL数据库------多表查询
数据库·mysql
ss2731 小时前
SpringBoot+vue养老院运营管理系统
vue.js·spring boot·后端
曹牧1 小时前
Oracle:拼音码
数据库·oracle
BD_Marathon2 小时前
【JavaWeb】日程管理03——准备数据库和实体类
数据库·oracle
用户841794814562 小时前
vue 甘特图 vxe-gantt table 依赖线的使用,配置连接线
vue.js
大学生资源网2 小时前
java毕业设计之面向校园的助力跑腿系统设计与实现源码(源码+文档+数据库)
java·数据库·mysql·毕业设计·源码·springboot