时间:2020-10-13来源:www.pcxitongcheng.com作者:电脑系统城
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文环境 python3.6.1 Mysql 5.7.18
1、安装模块
pip3 install pymysql
2、python操作
1) 获取查询数据
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = 'redhat' , db = 'homework' ,charset = 'utf8' ) # 创建游标 cursor = conn.cursor() # 执行SQL cursor.execute( "select * from student" ) #获取剩余结果的第一行数据 #row_1 = cursor.fetchone() #获取前n行数据 #row_2 = cursor.fetchmany(3) #获取所有查询数据 row_3 = cursor.fetchall() print (row_3) # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close() |
2、获取新创建数据的自增id
最后插入的一条数据id
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "Yu" import pymysql conn = pymysql.connect(host = '127.0.0.1' ,port = 3306 , user = 'root' , passwd = 'redhat' , db = 'db3' ) cursor = conn.cursor() effect_row = cursor.executemany( "insert into tb11(name,age) values(%s,%s)" , [( "yu" , "25" ),( "chao" , "26" )]) conn.commit() cursor.close() conn.close() # 获取自增id new_id = cursor.lastrowid print (new_id) |
3、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#! /usr/bin/env python # -*- coding:utf-8 -*- # __author__ = "Yu" import pymysql conn = pymysql.connect(host = '127.0.0.1' ,port = 3306 , user = 'root' , passwd = 'redhat' , db = 'db3' ) #游标设置为字典类型 cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) cursor.execute( "select * from tb11" ) row_1 = cursor.fetchone() print (row_1) conn.commit() cursor.close() conn.close() |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
2023-03-17
python flask项目打包成docker镜像发布的过程2023-03-17
python调试模块ipdb详解2023-03-17
python使用openai生成图像的超详细教程python cron定时任务触发接口自动化巡检 apscheduler报错:Run time of job …… next run at: ……)” was missed by misfire_grace_time参数 找到任务超时的根本原因...
2023-03-15