1、事务的ACID性质
事务具有4个特性:原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)和持续性(Durablility)。
以“银行转帐”为例:
-
原子性(Atomicity):组成事务处理的语句形成了一个逻辑单元,不能只执行其中的一部分。换句话说,事务是不可分割的最小单元。比如:银行转帐过程中,必须同时从一个帐户减去转帐金额,并加到另一个帐户中,只改变一个帐户是不合理的。
-
一致性(Consistency): 在事务处理执行前后,数据库是一致的。也就是说,事务应该正确的转换系统状态。比如:银行转帐过程中,要么转帐金额从一个帐户转入另一个帐户,要么两个帐户都不变,没有其他的情况。
-
隔离性(Isolation) :一个事务处理对另一个事务处理没有影响。就是说任何事务都不可能看到一个处在不完整状态下的事务。比如说,银行转帐过程中,在转帐事务没有提交之前,另一个转帐事务只能处于等待状态。
-
持续性(Durablility):事务处理的效果能够被永久保存下来。反过来说,事务应当能够承受所有的失败,包括服务器、进程、通信以及媒体失败等等。比如:银行转帐过程中,转帐后帐户的状态要能被保存下来。
2、事务状态
SET AUTOCOMMIT = 0 , 禁止自动提交 SET AUTOCOMMIT = 1, 开启自动提交START TRANSACTION:开始事务,autocommit设为0,如果已经有一个事务在运行,则会触发一个隐藏的COMMITCOMMIT:提交事务,保存更改,释放锁ROLLBACK:回滚本事务对数据库的所有更改,然后结束事务,释放锁SAVEPOINT savepoint_name:创建一个savepoint识别符来ROLLBACK TO SAVEPOINTROLLBACK TO SAVEPOINT savepoint_name:回滚到从savepoint_name开始对数据库的所有更改,这样就允许回滚事务中的一部分,保证更改的一个子集被提交SET TRANSACTION:允许设置事务的隔离级别LOCK TABLES:允许显式的锁住一个或多个table,会隐式的关闭当前打开的事务,建议在执行LOCK TABLES语句之前显式的commit或rollback。我们一般所以一般在事务代码里不会使用LOCK TABLES
3、事务操作
(1) 首先创建employee数据表:
mysql> create table employee( -> employeeID char(4), -&<div>本文来源gaodai^.ma#com搞#代!码网</div>gt; name varchar(20) not null, -> job varchar(20), -> departmentID int -> );Query OK, 0 rows affected (0.10 sec)mysql> insert into employee value ('7513' , 'Nora Edwar' , 'Programmer', 128);mysql> insert into employee value ('9006' , 'Candy Burn' , 'Systems Ad',128 );mysql> insert into employee value ( '9842' , 'Ben Smith' , 'DBA' , 42);mysql> insert into employee value ('9843', 'Pert Park' , 'DBA' , 42 );mysql> insert into employee value ('9845' , 'Ben Patel' , 'DBA' , 128 );mysql> insert into employee value ('9846' , 'Red Right' , null, 128 );mysql> insert into employee value ('9847' , 'Run Wild' , null , 128 );mysql> insert into employee value ('9848' , 'Rip This J' , null , 128 );mysql> insert into employee value ('9849' , 'Rip This J' , null , 128 );mysql> insert into employee value ( '9850' , 'Reader U' , null , 128 );mysql> insert into employee value ('6651', 'Ajay Patel' , 'Programmer', 128 );mysql> select * from employee;+------------+------------+------------+--------------+| employeeID | name | job | departmentID |+------------+------------+------------+--------------+| 6651 | Ajay Patel | Programmer | 128 || 7513 | Nora Edwar | Programmer | 128 || 9006 | Candy Burn | Systems Ad | 128 || 9842 | Ben Smith | DBA | 42 || 9843 | Pert Park | DBA | 42 || 9845 | Ben Patel | DBA | 128 || 9846 | Red Right | NULL | 128 || 9847 | Run Wild | NULL | 128 || 9848 | Rip This J | NULL | 128 || 9849 | Rip This J | NULL | 128 || 9850 | Reader U | NULL | 128 || 6651 | Ajay Patel | Programmer | 128 |+------------+------------+------------+--------------+