MySQL 并发,它是如何工作的,我是否需要在我的应用程序中处理它
我目前正在运行一个 MySQL 数据库.我所有的表都使用表引擎 InnoDB.
I am currently running a MySQL database. All of my tables are using the Table Engine InnoDB.
登录我的应用程序的每个人都可以查看记录,我担心在某些时候两个用户可能会同时更新或插入记录.MySQL 是否优雅地处理了这种类型的并发问题,还是我必须将其编程到我的代码中?
Everyone who logs into my application can view records and I am worried that at some point two users might update or insert a record at the same time. Does MySQL handle this type of concurrency issue gracefully, or is this something that I am going to have to program into my code?
如果我必须将它编程到我的代码中,您将如何处理这样的并发情况?
If I do have to program it into my code how do you go about handling a concurrency case like this?
推荐答案
SQL 语句是原子的.也就是说,如果你执行这样的事情:
SQL statements are atomic. That is, if you execute something like this:
UPDATE Cars SET Sold = Sold + 1
在此声明期间,没有人可以更改 Sold
变量.它总是加 1,即使其他人正在同时执行相同的语句.
Nobody can change the Sold
variable during this statement. It is always incremented by 1, even if somebody else is executing the same statement concurrently.
如果你有相互依赖的语句,就会出现问题:
The problem occurs if you have statements that depend on each other:
a = SELECT Sold FROM Cars;
UPDATE Cars SET Sold = a + 1;
在这些查询之间,另一个用户可以更改表 Cars 并更新 Sold.为了防止这种情况,请将其包装在一个事务中:
Between these queries, another user can change the table Cars and update Sold. To prevent this, wrap it in a transaction:
BEGIN;
a = SELECT Sold FROM Cars;
UPDATE Cars SET Sold = a + 1;
COMMIT;
InnoDB 支持事务,但 MyISAM 不支持.
Transactions are supported by InnoDB, but not by MyISAM.
相关文章