Home > Database > Mysql Tutorial > Mysql中的事务是什么如何使用_MySQL

Mysql中的事务是什么如何使用_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:25:59
Original
1174 people have browsed it

bitsCN.com 什么是事务?

事务是逻辑上的一组操作,组成这组操作的各个单元,要不全都成功要不全都失败,这个特性就是事务

注意:mysql数据支持事务,但是要求必须是innoDB存储引擎

解决这个问题:

mysql的事务解决这个问题,因为mysql的事务特性,要求这组操作,要不全都成功,要不全都失败,这样就避免了某个操作成功某个操作失败。利于数据的安全

如何使用:

(1)在执行sql语句之前,我们要开启事务 start transaction;

(2)正常执行我们的sql语句

(3)当sql语句执行完毕,存在两种情况:

1,全都成功,我们要将sql语句对数据库造成的影响提交到数据库中,committ

2,某些sql语句失败,我们执行rollback(回滚),将对数据库操作赶紧撤销


(注意:mysql数据支持事务,但是要求必须是innoDB存储引擎)
mysql> create table bank(name varchar(20),money decimal(5,1))engine=innodb defau
lt charset=utf8;

mysql> inset into bank values('shaotuo',1000),('laohu',5000);

mysql> select*from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 1000.0 |
| laohu | 5000.0 |
+---------+--------+

------没有成功“回滚”执行rollback
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.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> 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: 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> commit; //两个都成功后执行commit(只要不执行commit,sql语句不会对真实的数据库造成影响)
Query OK, 0 rows affected (0.05 sec)

mysql> select*from bank;
+---------+--------+
| name | money |
+---------+--------+
| shaotuo | 1500.0 |
| laohu | 4500.0 |
+---------+--------+bitsCN.com

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
MySQL stops process
From 1970-01-01 08:00:00
0
0
0
Error when installing mysql on linux
From 1970-01-01 08:00:00
0
0
0
phpstudy cannot start mysql?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template