且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MySQL 中锁定一行以供选择

更新时间:2023-02-05 12:06:00

您可以使用 SELECT FOR UPDATE.在您的事务中,开始选择您想要锁定"的行,如下所示:

You can use a SELECT FOR UPDATE. Inside your transaction, start out selecting the rows that you want to "lock", something like this:

 SELECT * from TABLE where id = 123 FOR UPDATE;

如果两个不同的事务同时尝试执行此操作,MySQL 将使第二个事务等待,直到第一个事务提交事务.这样,您就可以放心,第二个事务只会在第一个事务完成后查看该行.

If two different transactions try to do this at the same time, MySQL will make the second one wait until the first one has committed the transaction. That way, you'll be assured that the second transaction only looks at the row after the first one is done with it.