本篇对于Python操作MySQL主要使用两种方式:
原生模块 pymsql
ORM框架 SQLAchemy
一、pymysql |
pymsql是Python中操作MySQL的模块,其使用方法和mysqldb几乎相同
下载安装
pip3 install pymysql
使用操作
1、执行SQL
import pymysql # 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',passwd='123456', db='db1')
# 创建游标
cursor = conn.cursor() # 执行SQL,并返回收影响行数
effect_row = cursor.execute("select * from tb1")
# 执行SQL,并返回受影响行数
effect_row = cursor.executemany("insert into tb1(name,age)values(%s,%s)", [("小青", 20), ("小红", 20)]) # 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close() print(effect_row)
2、获取新创建数据自增ID
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='nining123456', db='db1')
cursor = conn.cursor()
cursor.executemany("insert into tb1(name,age)values(%s,%s)", [("小青", 20), ("小红", 20)])
conn.commit()
cursor.close()
conn.close() new_id = cursor.lastrowid
print(new_id)
3、获取查询数据
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',passwd='123456', db='db1')
cursor = conn.cursor()
effect_row = cursor.execute("select * from tb1") # 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
row_2 = cursor.fetchmany(3)
# 获取所有数据
row_3 = cursor.fetchall() conn.commit()
cursor.close()
conn.close() print(row_1)
print(row_2)
print(row_3)
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',passwd='nining123456', db='db1') # 输出的行为字典
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
effect_row = cursor.execute("select * from tb1") # 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
row_2 = cursor.fetchmany(3)
# 获取所有数据
row_3 = cursor.fetchall() conn.commit()
cursor.close()
conn.close() print(row_1)
print(row_2)
print(row_3)