mysql事务transaction 与 锁定lock

建表

create database yin_hang character set utf8 collate utf8_general_ci;

use yin_hang;

create table zhang_hao(
    id int(20) auto_increment not null primary key, 
    xing_ming varchar(50) not null, 
    jin_e int
);

insert into zhang_hao(xing_ming,jin_e) values('张三',100),('李四',100);

事务的出现, 考虑这样的一个经典例子:
张三账户转账100元到李四的账户
1,张三账户减去100元
2,李四账户增加100元
====================
默认自动提交

select @@autocommit;

+--------------+
| @@autocommit |
+--------------+
| 1 |
+--------------+
1 row in set (0.00 sec)

set @@autocommit=0;

Query OK, 0 rows affected (0.00 sec)

select @@autocommit;

+--------------+
| @@autocommit |
+--------------+
| 0 |
+--------------+

start transaction;
update zhang_hao set jin_e=0 where xing_ming='张三';
rollback;
commit;

回滚到自定义点

start transaction;
update zhang_hao set jin_e=0 where xing_ming='张三';
update zhang_hao set jin_e=200 where xing_ming='李四';
savepoint s1;
update zhang_hao set jin_e=250 where xing_ming='李四';
rollback to s1;
commit;

锁定 lock

数据库有一个特性, 允许多用户访问, 就会出现 并发性。

例如, 网上购物系统, 只剩下一本书, 张三,李四 同时进行网上购买剩下这本书

有可能他们都会买到这本书, 但是不符合现实,因为只有一本书

这样我们通过锁来实现 (read, write)

mysql> lock tables zhang_hao read;

mysql> select * from zhang_hao;

由于对账号表进行了读权限进行锁定,所以更新失败

mysql> update zhang_hao set jin_e=1000 where xing_ming='张三';

ERROR 1099 (HY000): Table 'zhang_hao' was locked with a READ lock and can't be updated

mysql> unlock tables;

解开锁之后,成功更新

mysql> update zhang_hao set jin_e=1000 where xing_ming='张三';

Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0

你可能感兴趣的:(mysql事务transaction 与 锁定lock)