Python pymysql模块安装并操作过程解析
py鱼 人气:3pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
本文环境 python3.6.1 Mysql 5.7.18
1、安装模块
pip3 install pymysql
2、python操作
1) 获取查询数据
#!/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
#! /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数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
#! /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()
加载全部内容