Pymysql小记+实战


连接

import pymysql

connection = pymysql.connect(
	host='localhost',
	user='root',
	password='pass_word',
	db='db_name',
	charset='utf8',
	cursorclass=pymsql.cursors.DictCursor
)
  • connection 对象常用方法
方法说明
cursor()获取游标对象
commit()提交事务
rollback()回滚事务
close()关闭数据库连接

获取游标

import pymysql
connection = pymysql.connect(...)

cursor = connection.cursor()
  • cursor 常用方法
方法说明
excute(operation[, parameters])执行单条指令
excutemany(operation, seq_of_params)批量执行指令(批量更新…)
fetchone()获取查询结果的下一条结果
fetchmany(size)获取指定数量的结果
fetchall()获取所有查询结果
close()关闭当前游标

执行指令并提交

  • cursor.excute()
  • cursor.excutemany()
  • connection.commit()

通过执行不同的 MySQL 指令实现

更详细的SQL指令,参考之前的这篇文章【点击查看】


import pymysql

connection = pymysql.connect('localhost', 'root', 
	'pass_word', 'my_db', charset='utf8')
# 获取游标
cursor = connection.cursor()
# ----------------------指令--------------------------------------
# 创建表 sql 指令
create_table_sql = '''create table mytable
    id int(20) not null primary key,
    name varchar(20) unicode not null,
    gender varchar(8) unicode not null,
    )engine=InnoDB default charset=utf8mb4;
    '''
# 插入一条数据指令
insert_one_sql = 'insert into mytable(id, name, gender) values(10010, "Bender", "Male")'
# 插入多条数据指令,注意占位符 %s
insert_many_sql = "insert into mytable values(%s, %s, %s)"
# 相应数据
datas = [[10011, "Leela", "Famale"],
		[10012, 'Fry', 'Male']]
# ...
# 其他指令参考之前文章[上文链接]
# https://blog.csdn.net/qq_45020818/article/details/121213264
# -----------------------------------------------------------------------
# 执行创建 表 指令
cursor.excute(create_table_sql)
# 执行插入单条数据指令
cursor.excute(insert_one_sql)
# 执行插入多条数据指令
cursor.excutemany(insert_many_sql, datas)
# 提交
connection.commit()
# ...

回滚

  • 发生错误时,回滚
import pymysql
try:
	connection = pymysql.connect(...)
	cursor = conection.cursor()
	cursor.excute('insert into mytable values(***,***,***)'
	connection.commit()
except:
	# 发生错误时回滚
	connection.rollback()

connection.close()

查询

  • fetchone()
  • fetchmany()
  • fetchall()
  • 配合 select ** from _table[where **] 语句使用

import pymysql

connection = pymysql.connect(...)	# 连接
cursor = connection.cursor()	# 获取游标
# 查询 sql语句
select_sql = 'select id,name,gender from mytable where id>10010'
# 执行查询指令
cursor.excute(select_sql)
# 获取所有查询结果
datas = cursor.fetchall()
# 遍历查询结果
for data in datas:
	print(f'id: {data["id"]}\t'  
		 f'name: {data["name"]}\t'
		 f'gender: {data["gender"]}')
# 关闭数据库连接
connection.close()

关闭

  • connection.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛定谔的壳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值