MySQL 知识量:16 - 40 - 165
管理事务的关键在于将SQL语句组分解为逻辑块,并明确规定什么时候回退。
MySQL使用以下语句标识事务的开始:
start transaction
MySQL不明确标识事务处理块在何处结束,事务一旦开始,会一直存在,直到被中断。
rollback命令用于回退(撤销)SQL语句,例如:
select * from people; start transaction; delete from people; select * from people; rollback; select * from people;
命令行实用程序界面的结果:
+----+----------+---------+--------+ | id | realName | realAge | sex | +----+----------+---------+--------+ | 1 | Susan | 12 | female | | 2 | Jame | 12 | male | | 3 | Bob | 12 | male | | 4 | Robot | 12 | male | | 5 | Jen | 12 | female | | 6 | Toney | 12 | male | | 8 | Alice | 12 | female | | 9 | Bonnie | 12 | male | | 10 | Ella | 12 | female | | 11 | Bill | 15 | male | | 12 | Limon | 14 | male | | 13 | Soen | 16 | male | +----+----------+---------+--------+ 12 rows in set (0.00 sec) /*第一次查询people的结果*/ Query OK, 0 rows affected (0.00 sec) /*开始事务处理*/ Query OK, 12 rows affected (0.00 sec) /*删除people*/ Empty set (0.00 sec) /*再次查询people*/ Query OK, 0 rows affected (0.01 sec) /*回退操作*/ +----+----------+---------+--------+ | id | realName | realAge | sex | +----+----------+---------+--------+ | 1 | Susan | 12 | female | | 2 | Jame | 12 | male | | 3 | Bob | 12 | male | | 4 | Robot | 12 | male | | 5 | Jen | 12 | female | | 6 | Toney | 12 | male | | 8 | Alice | 12 | female | | 9 | Bonnie | 12 | male | | 10 | Ella | 12 | female | | 11 | Bill | 15 | male | | 12 | Limon | 14 | male | | 13 | Soen | 16 | male | +----+----------+---------+--------+ 12 rows in set (0.00 sec) /*回退后再一次查询people*/
一般的SQL语句都是自动进行提交的,即隐式提交(自动执行)。但是,在事务处理块中,提交不会隐式进行,要使用明确的提交方式,需要使用commit语句。
people表如下:
+----+----------+---------+--------+ | id | realName | realAge | sex | +----+----------+---------+--------+ | 1 | Susan | 12 | female | | 2 | Jame | 12 | male | | 3 | Bob | 12 | male | | 4 | Robot | 12 | male | | 5 | Jen | 12 | female | | 6 | Toney | 12 | male | | 8 | Alice | 12 | female | | 9 | Bonnie | 12 | male | | 10 | Ella | 12 | female | | 11 | Bill | 15 | male | | 12 | Limon | 14 | male | | 13 | Soen | 16 | male | +----+----------+---------+--------+
删除Bill和Ella:
start transaction; delete from people where realName='Bill'; delete from people where realName='Ella'; commit;
结果:
+----+----------+---------+--------+ | id | realName | realAge | sex | +----+----------+---------+--------+ | 1 | Susan | 12 | female | | 2 | Jame | 12 | male | | 3 | Bob | 12 | male | | 4 | Robot | 12 | male | | 5 | Jen | 12 | female | | 6 | Toney | 12 | male | | 8 | Alice | 12 | female | | 9 | Bonnie | 12 | male | | 12 | Limon | 14 | male | | 13 | Soen | 16 | male | +----+----------+---------+--------+
注意:当commit或rollback语句执行后,事务会自动关闭,后面的语句会默认隐式提交。
使用rollback和commit语句可以撤销和提交整个事务,但是,对于复杂的事务可能仅需要部分回退和提交。要使用回退部分事务,必须在事务处理块中合适的位置放置占位符,即保留点。
在MySQL中创建保留点,可以使用savepoint语句。例如:设置保留点p1。
savepoint p1;
重要的一点是,可以在SQL语句中设置任意多的保留点,而且越多越好,这样可以根据需要选择回退位置,从而更加灵活的进行回退。
保留点在事务处理完成(即执行一条rollback或commit)后自动释放,也可以使用release savepoint明确释放。
Copyright © 2017-Now pnotes.cn. All Rights Reserved.
编程学习笔记 保留所有权利
MARK:3.0.0.20240214.P35
From 2017.2.6