Python培训
               
            
            400-996-5531
Python就业的一个方向就是做web,而web后端一定是离不开MySQL数据库的,所以,在本文中就给大家介绍一下,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
以上就是通过Python操作MySQL数据库的基础内容。
免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。
填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!
Copyright ©  Tedu.cn All Rights Reserved 京ICP备08000853号-56 
京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有