MySQL表锁与事务
本文关键字:事务 MySQL | 更新日期: 2023-09-27 18:08:17
我想知道是否有任何方法可以锁定MySQL表而不隐式提交事务。
假设我有两个表(table_1, table_2),我在事务的同时向这两个表插入数据。并且我需要锁定'table_2',以便其他用户不能写入/修改'table_2',直到事务完成。我的问题是,当我锁定表_2时,事务是隐式提交的。是的,我知道在MySQL文档
中有解释locktables不是事务安全的,并且隐式地提交任何活动在试图锁定表之前执行事务
我想知道是否有其他事务安全的方法来执行表锁定。
这是我的c#代码段MySQLTransaction trans = conn.BeginTransaction();
command.Transaction = trans;
command.CommandText = "INSERT INTO table_1 VALUES ('val1', 'val2')";
command.ExecuteNonQuery();
command.CommandText = "LOCK TABLES table_2 WRITE";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO table_2 VALUES ('val1', 'val2')";
command.ExecuteNonQuery();
command.CommandText = "RELEASE TABLES";
command.ExecuteNonQuery();
trans.Commit();
在没有提交事务的情况下锁定和插入数据到'table_2'有什么想法吗?Thanks in advance
如果您打算以正确的方式锁定,以达到您的原始意图,请预先锁定两个表:
LOCK TABLES table_1 WRITE, table_2 WRITE
INSERT INTO table_1 VALUES ('val1', 'val2')
INSERT INTO table_2 VALUES ('val1', 'val2')
UNLOCK TABLES
本地MySQL提供了这个(虽然我从来没有测试过它是否会通过连接器工作-但我不明白为什么不。)
一旦你有了锁,没有人可以进入。
试试这个,用c#写的
using (var con = new MySqlConnection { ConnectionString = "YourConnectionString" })
{
con.Open();
MySqlTransaction trans = con.BeginTransaction();
MySqlCommand command = con.CreateCommand();
try
{
command.CommandText = @"LOCK TABLES table_1 WRITE, table_2 WRITE;
INSERT INTO table_1 VALUES ('val1', 'val2');
INSERT INTO table_2 VALUES ('val1', 'val2');
UNLOCK TABLES;";
command.ExecuteNonQuery();
trans.Commit();
}
catch(MySqlException ex)
{
trans.Rollback();
conn.msgErr(ex.Message + " sql query error.");
conn.msgErr("Neither record was written to database.");
}
finally
{
command.Dispose();
trans.Dispose();
}
}