Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

MySQL concurrency, how does it work and do I need to handle it in my application

I am currently running a MySQL database. All of my tables are using the Table Engine InnoDB.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SQL statements are atomic. That is, if you execute something like this:

UPDATE Cars SET Sold = 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;

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;

Transactions are supported by InnoDB, but not by MyISAM.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...