MySQL并发,它如何工作,我需要在我的应用程序中处理它 [英] MySQL concurrency, how does it work and do I need to handle it in my application

查看:60
本文介绍了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.

这篇关于MySQL并发,它如何工作,我需要在我的应用程序中处理它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆