Python PyMySQL:数据库事务


#Python PyMySQL


简介

  • 开启事务:conn.begin()
  • 提交事务:conn.commit()
  • 回滚事务:conn.rollback()

示例

建表

在 blog 库下建表:

create table `user_info` (
    `id` bigint unsigned not null auto_increment,
    `name` varchar(45) not null default '',
    primary key (`id`)
) engine = InnoDB default charset = utf8mb4;

插入数据,数据内容如下:

mysql> select * from user_info;
+----+---------+
| id | name    |
+----+---------+
|  2 | name001 |
|  3 | name002 |
|  4 | name003 |
|  5 | name004 |
|  6 | name005 |
|  7 | name006 |
+----+---------+
6 rows in set (0.01 sec)

示例1:开启和提交事务

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='123456',
                       port=3306,
                       database='blog',
                       autocommit=True
                       )
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

conn.begin()
cursor.execute('INSERT INTO `user_info` (name) values(%s);', ['name100'])
cursor.execute('INSERT INTO `user_info` (name) values(%s);', ['name101'])
conn.commit()


cursor.close()
conn.close()

示例2:回滚事务

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       user='root',
                       password='123456',
                       port=3306,
                       database='blog',
                       autocommit=True
                       )
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

try:
    conn.begin()
    cursor.execute('INSERT INTO `user_info` (name) values(%s);', ['name102'])
    cursor.execute('INSERT INTO `user_info` (name) values(%s);', ['name103'])
    raise Exception('模拟异常')
    conn.commit()
except Exception as ex:
    print('出现异常,回滚')
    conn.rollback()


cursor.close()
conn.close()


( 本文完 )