一、pymysql
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,我们今天来说下pymsql用法。MySQLdb的只有在python2 里面使用的,在python3里面需要用pymysql。
二、安装pymysql
pip3 install pymysql
三、使用
3.1 连接mysql
# -*- coding: UTF-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host=‘172.16.200.49‘, port=3306, user=‘bigberg‘, password=‘111111‘, db=‘study‘) # 创建游标 cursor = conn.cursor() # 执行SQL,并返回受影响行数 effect_row = cursor.execute("select * from student") print(effect_row) # 执行SQL,并返回受影响行数 # data = [ # (‘S1‘,‘2018-04-21‘,‘M‘), # (‘S2‘,‘2018-05-11‘,‘F‘), # (‘S3‘,‘2018-04-25‘,‘M‘) # ] # sql = "insert into student (name,register_date,gender) values (%s,%s,%s)" # effect_row = cursor.executemany(sql,data) # 提交,不然无法保存 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close()
3.2 获取查询的数据
# -*- coding: UTF-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host=‘172.16.200.49‘, port=3306, user=‘bigberg‘, password=‘111111‘, db=‘study‘) cursor = conn.cursor() sql = "select * from student where stu_id>3" cursor.execute(sql) # 获取第一行数据 # result = cursor.fetchone() # 获取前n条数据 # result = cursor.fetchmany(3) # 获取所有数据 result = cursor.fetchall() print(result) conn.commit() cursor.close() conn.close()
3.3 fetch数据类型
import pymysql # 创建连接 conn = pymysql.connect(host=‘172.16.200.49‘, port=3306, user=‘bigberg‘, password=‘111111‘, db=‘study‘,) # 游标设置为字典类型 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)