<pre name="code" class="html">Session 1:
mysql> use zjzc;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from test;
+------+------+
| id | name |
+------+------+
| NULL | a |
| 2 | b |
| 3 | c |
| 1 | a |
+------+------+
4 rows in set (0.00 sec)
mysql> lock table test read;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from test;
+------+------+
| id | name |
+------+------+
| NULL | a |
| 2 | b |
| 3 | c |
| 1 | a |
+------+------+
4 rows in set (0.00 sec)
mysql> insert into test values(4,'a');
ERROR 1099 (HY000): Table 'test' was locked with a READ lock and can't be updated
Session 2:
Database changed
mysql> select * from test;
+------+------+
| id | name |
+------+------+
| NULL | a |
| 2 | b |
| 3 | c |
| 1 | a |
+------+------+
4 rows in set (0.00 sec)
mysql> insert into test values(4,'a');
由于session 1加了只读锁,session2无法插入
session 2也可以加只读锁;
mysql> lock table test read;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test values(4,'a');
ERROR 1099 (HY000): Table 'test' was locked with a READ lock and can't be updated
一个session只能为自己获取锁和释放锁,不能为其他session获取锁,也不能释放由其他session保持的锁。
UNLOCK TABLES还还以用来释放FLUSH TABLES WITH READ LOCKS获取的全局锁,该锁锁定所有库的所有表。
/*************
[root@wx03 sbin]# perl a2.pl
$XDATE is 20160823132742
DBD::mysql::db do failed: Table 't1' was locked with a READ lock and can't be updated at a2.pl line 12.
[root@wx03 sbin]# cat a2.pl
use DBI;
use POSIX;
$db_name='scan';
$ip='127.0.0.1';
$user="root";
$passwd="R00t,uHagt.0511";
$dbh = DBI->connect("dbi:mysql:database=$db_name;host=$ip;port=3306",$user,$passwd
) or die "can't connect to database ". DBI-errstr;
my $XDATE = strftime("%Y%m%d%H%M%S",localtime());
print "\$XDATE is $XDATE\n";
$dbh->do("lock table t1 read") or die $dbh->errstr ;
$dbh->do("insert into t1 values(90)");
$dbh->disconnect;
[root@wx03 sbin]# perl a2.pl
$XDATE is 20160823132747
DBD::mysql::db do failed: Table 't1' was locked with a READ lock and can't be updated at a2.pl line 12.