繁星淼淼
什么是事务?事务是逻辑上的一组操作,组成这组操作的各个单元,要不全都成功要不全都失败,这个特性就是事务注意:mysql数据支持事务,但是要求必须是innoDB存储引擎解决这个问题:mysql的事务解决这个问题,因为mysql的事务特性,要求这组操作,要不全都成功,要不全都失败,这样就避免了某个操作成功某个操作失败。利于数据的安全如何使用:(1)在执行sql语句之前,我们要开启事务 start transaction;(2)正常执行我们的sql语句(3)当sql语句执行完毕,存在两种情况:1,全都成功,我们要将sql语句对数据库造成的影响提交到数据库中,committ2,某些sql语句失败,我们执行rollback(回滚),将对数据库操作赶紧撤销(注意:mysql数据支持事务,但是要求必须是innoDB存储引擎)mysql> create table bank(name varchar(20),money decimal(5,1))engine=innodb default charset=utf8;mysql> inset into bank values('shaotuo',1000),('laohu',5000);mysql> select*from bank;+---------+--------+| name | money |+---------+--------+| shaotuo | 1000.0 || laohu | 5000.0 |+---------+--------+------没有成功“回滚”执行rollbackmysql> 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.00 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> update bank set moey=money-500 where name='laohu';ERROR 1054 (42S22): Unknown column 'moey' in 'field list'mysql> rollback; //只要有一个不成功,执行rollback操作Query OK, 0 rows affected (0.01 sec)mysql> select*from bank;+---------+--------+| name | money |+---------+--------+| shaotuo | 1000.0 || laohu | 5000.0 |+---------+--------+------成功之后 进行commit操作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.01 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> update bank set money=money-500 where name='laohu';Query OK, 1 row affected (0.00 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> commit; //两个都成功后执行commit(只要不执行commit,sql语句不会对真实的数据库造成影响)Query OK, 0 rows affected (0.05 sec)mysql> select*from bank;+---------+--------+| name | money |+---------+--------+| shaotuo | 1500.0 || laohu | 4500.0 |+---------+--------+