Python 使用操作MySQL
第一步:
安装mysql数据库并创建号表、字段。安装python即pycharm环境。(详细步聚这篇就省略了)
第二步:
mysqlclient-1.3.12-cp36-cp36m-win_amd64.whl
安装命令:pipinstall mysqlclient-1.3.12-cp36-cp36m-win_amd64.whl
第三步:
python中使用pymysql连接mysql的库,安装命令:pip install pymysql
第四步:
查询数据、插入数据,编写如下Python代码:
# -*- coding: UTF-8-*-
import pymysql #导入pymysql库
import time #导入系统time库
#插入时间变量定义,默认读取本地时间,并格式化时间格式。
create_time =time.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time()))
def readSQL():
#查询SQL语句
sql="SELECTid,`apiname`,apiurl from apitest_apistep where apitest_apistep.Apitest_id=2"
#打开MySQL数据库连接
coon = pymysql.connect(user='root',passwd='test123456',db='autotest',port=3306,host='127.0.0.1',charset='utf8')
#获取数据库操作游标
cursor = coon.cursor()
#执行MySQL查询语句
aa=cursor.execute(sql)
#获取执行查询语句后的结果数据列表
info = cursor.fetchmany(aa)
print("查询数据成功:"+info)
# 提交
coon.commit()
#关闭游标
cursor.close()
#关闭连接
coon.close()
def writeSQL():
#写入SQL语句
sql = "INSERTINTO `apitest_apistep` (`apiname`,`apiurl`,`apiparamvalue`,`apimethod`,`apiresult`, `apistatus`,`create_time`,`Apitest_id`,apistep,apiresponse) VALUES('支付','{seturl}/login','null','get','0','1', '%s', '2','第三步','null');" % (create_time)
#打开MySQL数据库连接
coon = pymysql.connect(user='root',passwd='test123456',db='autotest',port=3306,host='127.0.0.1',charset='utf8')
#获取数据库操作游标
cursor = coon.cursor()
#执行MySQL查询语句
aa=cursor.execute(sql)
#获取执行查询语句后的结果数据列表
info = cursor.fetchmany(aa)
print("插入接口数据成功")
# 提交
coon.commit()
#关闭游标
cursor.close()
#关闭连接
coon.close()
if __name__ == '__main__': #主函数入口
readSQL() #查询数据函数
writeSQL() #写入数据函数
print ('Done!')
第五步:
运行代码,运行结果如下:
C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe D:/autotest_platform/python_mysql.py
查询数据成功:((1, '登录', '{seturl}/login'), (2, '购物', '{seturl}/login'), (4, '支付', '{seturl}/login'), (5, '支付', '{seturl}/login'), (6, '支付', '{seturl}/login'))
插入接口数据成功
Done!
Process finished with exit code 0