自动化测试22
python操作mysql数据库需要使用到mysqlclient库。
安装:pip install mysqlclient
python连接mysql数据库分以下步骤:
1、与mysql建立连接;
2、获取游标;
3、执行sql语句;
4、fetch查询结果或commit修改结果;
5、关闭游标;
6、关闭mysql连接。
完整示例如下:
# -*- coding:utf-8 -*- import MySQLdb from readConfig import get_config_values from utils.resutltodict import dict_fetchall def 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 qryset if __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://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes
来自:https://blog.csdn.net/weixin_30633507/article/details/98081097?ops_request_misc=%25257B%252522request%25255Fid%252522%25253A%252522160980878416780258063876%252522%25252C%252522scm%252522%25253A%25252220140713.130102334.pc%25255Fall.%252522%25257D&request_id=160980878416780258063876&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-19-98081097.pc_search_result_no_baidu_js&utm_term=python%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E6%A1%86%E6%9E%B6