博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python接口自动化测试框架实现之操作mysq数据库
阅读量:4555 次
发布时间:2019-06-08

本文共 1156 字,大约阅读时间需要 3 分钟。

python操作mysql数据库需要使用到mysqlclient库。

安装:pip install mysqlclient

python连接mysql数据库分以下步骤:

1、与mysql建立连接;

2、获取游标;

3、执行sql语句;

4、fetch查询结果或commit修改结果;

5、关闭游标;

6、关闭mysql连接。

 

完整示例如下:

 

# -*- coding:utf-8 -*-import MySQLdbfrom readConfig import get_config_valuesfrom utils.resutltodict import dict_fetchalldef execute_sql_query(sql, params):    """    执行mysql sql查询语句    :param sql: sql语句,变量使用%s占位    :param params: %s对应的变量,必须是元祖(tuple)    :return: queryset    """    conn = MySQLdb.connect(host=get_config_values('mysql', 'host'), port=int(get_config_values('mysql', 'port')),                       user=get_config_values('mysql', 'user'), passwd=get_config_values('mysql', 'password'),                       db=get_config_values('mysql', 'database'), charset='utf8')    cursor = conn.cursor()    cursor.execute(sql, params)    qryset = dict_fetchall(cursor=cursor)    cursor.close()    conn.close()    return qrysetif __name__ == '__main__':    sql = """SELECT * FROM asset_devices where companyid_id=%s"""    params = (25,)    result = execute_sql_query(sql=sql, params=params)    print(result)

mysqlclient的详细使用请参考官文:

 

转载于:https://www.cnblogs.com/ianduin/p/8556656.html

你可能感兴趣的文章
z变换
查看>>
Python - 静态函数(staticmethod), 类函数(classmethod), 成员函数
查看>>
Spring基础2
查看>>
【灵异短篇】这个夜晚有点凉
查看>>
一点小问题
查看>>
pytest 10 skip跳过测试用例
查看>>
MVC身份验证及权限管理
查看>>
It was not possible to find any compatible framework version
查看>>
nodejs概述
查看>>
关于8.0.15版本的mysql下载与安装
查看>>
Redis主从复制看这篇就够了
查看>>
部署和调优 2.3 tomcat中JDK安装
查看>>
洛谷 P1202 [USACO1.1]黑色星期五Friday the Thirteenth 题解
查看>>
(4.20)SQL Server数据库启动过程,以及启动不起来的各种问题的分析及解决技巧...
查看>>
基本数据类型(数字和字符串)
查看>>
函数__装饰器
查看>>
linux system函数分析
查看>>
前端优化措施
查看>>
论学习汉语和学习编程的异同点
查看>>
linux img文件压缩及解压
查看>>