【mysql】【04】mysql 锁

1.myisam存储引擎,表锁

查看表锁命令
show open tables;
锁表命令
lock table logging_event_exception read,rabbitmq_messge_log write;
解锁
unlock tables;

1.1读锁
session1 给表test加读锁
session1可以读test,不可以写test表,不可读写其他表
sesison2可以读test,阻塞写test表,可以读写其他表

1.2写锁
session1 给表test加写锁
session1 可以读可以写test,不可读写其他表
session2 阻塞读写test,可以读写其他表

1.3总结
myisam 在执行查询前,会自动给设计的表加读锁,在执行增删改操作前,会自动给涉及的表加写锁

读锁会阻塞写,但是不会阻塞读,写锁会把读写都堵塞了。

1.4查看锁的情况
show status like ‘table%’

Table_locks_immediate 参数表级锁时立即获取锁的次数
Table_locks_waited 参加表级锁时不能立即获取锁的次数

1.5myisam 和innodb的区别
innodb支持事务,innodb采用行级锁、
查看表的存储引擎

show create table sys_log

2.行锁
2.1事务的ACID

原子性:atomic
一致性:consistent
隔离性:isolation 事务处理的中间状态对外部不可见
持久性:durable

2.2并发事务带来的问题
脏读 事务A读到了事务B已经修改但是尚未提交的数据
不可重复读 事务A读到了事务B已经提交的数据
幻读 事务A读到了事务B尚未提交的新增数据

2.2.1不可重复读
id name age status
1 yinzhen 29 2
2 lixia 29 3
事务A读取了记录1 age 29,事务B对事务进行了记录1更新为30更新提交,事务A在读记录1时,内容发生改变
2.2.2脏读
事务A把记录1的age改成30,还没有提交事务,事务B读到了记录1的age为30
2.2.3幻读
事务A把所有记录的状态改成了2,事务B新增了一条记录2状态为3,对事务A来说像是幻读了。

2.3事务的隔离级别

未提交读 什么都不能避免
已提交读 可以避免脏读
可重复读 可以避免脏读和不可重复读
序列化 都可以避免

2.4查询数据库事务隔离级别

show variables like 'tx_isolation'

2.5索引失效,行锁变表锁
varchar 类型的字段加了索引,过滤时如果不加单引号,行锁变表锁

创建test表,在status 上建立索引
CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `create_time` timestamp NULL DEFAULT NULL,
  `status` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `test_status` (`status`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

create index test_status on test(status)

show index from test

set autocommit = 0;

explain select * from test where status = 2

update test set name = 'ceshi1'  where status = 2

show open tables from test

commit;

show open tables from test

set autocommit = 1;

2.6加索引后会减少锁的行数(不知道对不对,自己这么理解的)

锁的行数为8行
explain select * from test where create_time > '2018-01-12' and create_time < '2019-01-01'

1    SIMPLE    test    ALL                    8    Using where
在create_time加上索引后 锁1行
create index test_createTime on test(create_time)
explain select * from test where create_time > '2018-01-12' and create_time < '2019-01-01'
1    SIMPLE    test    range    test_createTime    test_createTime    5        1    Using where

2.7查看行锁的情况

show status like 'innodb_row_lock%'

Innodb_row_lock_current_waits
Innodb_row_lock_time
Innodb_row_lock_time_avg
Innodb_row_lock_time_max
Innodb_row_lock_waits
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值