PyMysql以及事务

pymsql是Python中操作MySQL的模块,其使用方法和py2的MySQLdb几乎相同。
# coding=utf-8
import pymysql

conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='123',db='s4')   #连接mysql,必须存在数据库

cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)  #获取光标,括号里面的参数是使得到的数据以{'字段':数据}的形式输出,默认是以元组输出


r1=cursor.execute('create table test(id int primary key auto_increment,name varchar(20))')# execute即使执行mysql语句


r2=cursor.execute("insert into test values ('alex'),('bart'),('alvin'),('lily')")#返回值是添加的行数
print('r2=',r2)

ret=cursor.execute('select * from test')

f1=cursor.fetchone()#fetchone()取一条记录
print('f1=',f1)

f2=cursor.fetchmany(2)#fetchmany(number)取n条数据
print('f2=',f2)

cursor.scroll(-2,mode='relative')#移动光标位置,relative为相对原来位置
f3=cursor.fetchone()
print('f3=',f3)

cursor.scroll(1,mode='absolute')#移动光标,absolute为与开头的绝对位置
f4=cursor.fetchall()
print('f4=',f4)

conn.commit() #只有commit以后记录才真正被写入

cursor.close()
conn.close()

事务

事务指逻辑上的一组操作,组成这组操作的各个单元,要不全部成功,要不全部不成功。

数据库开启事务命令     

--        start transaction 开启事务
--        Rollback 回滚事务,即撤销指定的sql语句(只能回退insert delete update语句),回滚到上一次commit的位置
--        Commit 提交事务,提交未存储的事务
-- 
--        savepoint 保留点 ,事务处理中设置的临时占位符 你可以对它发布回退(与整个事务回退不同) 

实例

--创建表
create table account(
       id int primary key auto_increment,
       name varchar (25),
       balance double
);

insert into account values (1,'alex',8000),(2,'ego',8000);

-- +----+------+---------+
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    8000 |
-- |  2 | ego  |    8000 |
-- +----+------+---------+


start transaction ;--开始事务

update account set balance=balance-5000 where name='alex';
select * from account;
-- +----+------+---------+ --此时数据并没有写入数据库,只是显示命令的结果,除非在操作下面写commit
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    3000 |
-- |  2 | ego  |    8000 |
-- +----+------+---------+

savepoint update1;         --设置保留点

update account set balance=balance+5000 where name='ego';
select * from account;

-- +----+------+---------+ --一样数据没有写入数据库
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    3000 |
-- |  2 | ego  |   13000 |
-- +----+------+---------+

savepoint update2;

rollback to update1;  --回滚至操作update1处,update1以上的操作任然存在,update1下的操作将全被取消
select * from account;

-- +----+------+---------+
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    3000 |
-- |  2 | ego  |    8000 |
-- +----+------+---------+

rollback ; --直接回滚,则会回滚自前面的commit处,如果没有commit就一直回滚至开头
-- +----+------+---------+
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    8000 |
-- |  2 | ego  |    8000 |
-- +----+------+---------+

commit ; --提交数据,此时数据才真正写入数据库
select * from account;

-- +----+------+---------+
-- | id | name | balance |
-- +----+------+---------+
-- |  1 | alex |    8000 |
-- |  2 | ego  |    8000 |
-- +----+------+---------+

python的pymysql开启事务

# coding=utf-8
import pymysql

#添加数据

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='yyy')

cursor = conn.cursor()


try:
    insertSQL0="INSERT INTO ACCOUNT2 (name,balance) VALUES ('bart',1000)"
    insertSQL1="UPDATE account2 set balance=balance-30 WHERE name='alex'"
    insertSQL2="UPDATE account2 set balance=balance+30 WHERE name='ego'"

    cursor = conn.cursor()

    cursor.execute(insertSQL0)
    conn.commit()

    cursor.execute(insertSQL1)
    raise Exception        #模拟出现错误
    cursor.execute(insertSQL2)
    cursor.close()
    conn.commit()

except Exception as e:

    conn.rollback()      #回滚
    conn.commit()


cursor.close()
conn.close()

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python pymysql 是一个Python的MySQL数据库驱动程序,它可以让我们方便地使用Python操作MySQL数据库。而事务是指作为一个单独的、不可分割的工作单位执行的一系列操作,只有所有操作都执行成功,才能提交事务;如果任意一个操作失败,就必须回滚事务,撤销已经执行的所有操作。下面介绍一下Python pymysql 中的事务处理。 在 Python pymysql 中,可以使用 connection 对象的 begin() 方法开启一个事务,使用 commit() 方法提交事务,使用 rollback() 方法回滚事务。当开启事务后,在所有的操作中,只有最后执行 commit() 才会将所有的操作提交到数据库中。 例如,下面的代码演示了如何使用 Python pymysql 开启事务、插入数据、更新数据和提交事务: ``` import pymysql # 连接数据库 conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test') try: # 开启事务 conn.begin() # 插入数据 cursor = conn.cursor() cursor.execute("INSERT INTO student (name, age) VALUES ('Tom', 18)") # 更新数据 cursor.execute("UPDATE student SET age = 20 WHERE name = 'Tom'") # 提交事务 conn.commit() except Exception as e: # 回滚事务 conn.rollback() finally: # 关闭连接 conn.close() ``` 在上面的代码中,我们使用了 try...except...finally 来处理异常和关闭连接,使用 conn.begin() 开启事务,使用 conn.commit() 提交事务,使用 conn.rollback() 回滚事务。注意,如果在执行过程中出现了异常,就会跳转到 except 语句块,执行回滚操作,撤销已经执行的所有操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值