python cursor游标重置位置scroll_MySQL的游标

python操作mysql

安装

python操作mysql数据库,主要就是通过pymysql模块

pip install pymysql

操作流程

1)建立数据库连接对象 conn

2)通过 conn 创建操作sql的 游标对象

3)编写sql交给 cursor 执行

4)如果是查询,通过 cursor对象 获取结果

5)操作完毕,端口操作与连接

代码步骤

注意

1.对记录增删改默认需要commit()

准备

import pymysql

一.建立连接

conn = pymysql.connect(user='root', passwd='root', database='t5')

二.获取游标对象

#注:游标不设置参数,查询的结果就是数据元组,数据没有标识性

#设置pymysql.cursors.DictCursor,查询的结果是字典,key是表的字段cursor = conn.cursor(pymysql.cursors.DictCursor)

三.增删改查

创建表

sql1="create table zx(id int)"

cursor.execute(sql1)

#单条添加

sql2='insert into zx values(%s)'

cursor.execute(sql2,(1,))

cursor.execute(sql2,(2,))

cursor.execute(sql2,(3,))

conn.commit()

#多条添加

cursor.executemany(sql2, [(4,), (5,)])

conn.commit()

sql3="delete from zx where id =%s"

cursor.execute(sql3,3)

conn.commit()

sql4='update zx set id=10 where id =2'

cursor.execute(sql4)

conn.commit()

sql5='select * from zx'

cursor.execute(sql5)

#fetchone() 偏移一条取出

r1=cursor.fetchone()

print(r1)

#fetchmany(n) 偏移n条取出

r2=cursor.fetchmany(1)

print(r2)

#fetchall() 偏移剩余全部

r3=cursor.fetchall()

print(r3)

结果

{'id': 1}

[{'id': 10}]

[{'id': 4}, {'id': 5}]

结束

#释放端口与连接

cursor.close()

conn.close()

游标其他用法

# 操作游标

# cursor.scroll(0, 'absolute') # absolute绝对偏移,游标重置,从头开始偏移

cursor.scroll(-2, 'relative') # relative相对偏移,游标在当前位置进行左右偏移

事务

#转账案例

try:

sql1 = 'update t2 set money=money-1 where name="tom"'

r1 = cursor.execute(sql1)

sql2 = 'update t2 set money=money+1 where name="ruakei"' # 转入的人不存在

r2 = cursor.execute(sql2)

except:

print('转账执行异常')

conn.rollback()

else:

print('转账没有异常')

if r1 == 1 and r2 == 1:

print('转账成功')

conn.commit()

else:

conn.rollback()

sql注入攻击

不要自己拼接参数,交给pymysql占位填充!

sql = 'select * from user where name=%s and password=%s'

row = cursor.execute(sql, (usr, pwd))

if row:

print('登录成功')

else:

print('登录失败')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值