1,什么是事务?
我们在实际处理某个问题的时候,需要多条sql语句在一起才能完成某个操作,这组sql语句的关系是,要不都执行成功,要不都执行失败,这个特性就是事务
2,事务的定义:
事务是指逻辑上的一组操作,组成这组操作的各个单元,要不全都成功要不全都失败,有了事务,可以保证数据在业务逻辑上是安全的
3,使用事务案例:
//在转账系统中,需要保证一个人将钱从帐号中移除,另一个人在帐号中增加某些金额,但是如果有一个步骤出错,这次转账失败(使用mysql的事务)
mysql> update bank set money=money-500 where nme='laohu';
ERROR 1054 (42S22): Unknown column 'nme' in 'where clause'
mysql> select * from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 3500.0 |
| laohu | 3500.0 |
+---------+--------+
2 rows in set (0.00 sec)
mysql> rollback;
Query OK, 0 rows affected (0.05 sec)
mysql> select * from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 3000.0 |
| laohu | 3500.0 |
+---------+--------+
2 rows in set (0.00 sec)
mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)
mysql> update bank set money=money+500 where name='shaotuo';
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update bank set money=money-500 where name='laohu';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from bank;//1、这里其实没有成功,在打开一个mysql窗口,查看就没有改变
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 3500.0 |
| laohu | 3000.0 |
+---------+--------+
2 rows in set (0.00 sec)
mysql> commit;//2、执行这个之后就会真的提交到数据库,会改变
Query OK, 0 rows affected (0.05 sec)
mysql> select * from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 3500.0 |
| laohu | 3000.0 |
+---------+--------+
2 rows in set (0.00 sec)
mysql>