I have some question ... example: a user will buy something for his USD
Use TRANSACTION and if it fails you can rollback.
For example, assume the current balance is $20.
Connection A Connection B
======================= ===========================
BEGIN TRANSACTION
BEGIN TRANSACTION
SELECT AccountBalance
SELECT AccountBalance
--returns $20
--sufficient balance,
--proceed with purchase
--returns $20
--sufficient balance,
--proceed with purchase
--update acquires exclusive lock
UPDATE SET AccountBalance
= AccountBalance - 20
--update blocked due
UPDATE SET AccountBalance
= AccountBalance - 20
--order complete
COMMIT TRANSACTION
--update proceeds
--database triggers
--constraint violation
--"AccountBalance >= 0"
ROLLBACK TRANSACTION
First off, you have to use transactions, but that's not enough. In your transaction, you can use SELECT FOR UPDATE.
It's basically saying, "I'm going to update the records I'm selecting", so it's setting the same locks that an UPDATE
would set. But remember this has to happen inside a transaction with autocommit turned off.
you need to use TRANSACTION at the SERIALIZABLE isolation level.
This is how I used to do it many years ago..
results = query("UPDATE table SET value=value-5 WHERE value>=5 AND ID=1")
if (results == 1) YEY!
(Is this still a reliable method?)
You need to use Data revision for MySQL UPDATE.