简体   繁体   中英

How to block table in booking?

How to block table to booking? My booking table has from_datetime and to_datetime fields. I would like to avoid situation, when two users book something in the same time.

My attempts:

TERMINAL 1: - user1

LOCK TABLE booking READ;
INSERT INTO booking VALUES ('2019-01-01 12:00:00', '2019-01-01 14:00:00');

Now table booking should be locked, and other users should not be able to read from its, but...

TERMINAL 2: - user2

SELECT * from booking 

I have results... Why? This should be blocked until I do in TERMINAL 1:

unlock tables;

You need to use LOCK TABLE booking WRITE; . That indicates that you're going to be writing to the table, and you need to block everyone else from reading and writing the table.

A READ lock means that you're only going to read the table. It blocks other users from writing to the table, so that all your reads access consistent table contents. But it doesn't block other users from reading the table.

However, if you're using InnoDB you should use transactions rather than table locks. This is more fine-grained, and figures out what to lock automatically. Your code would look something like this:

START TRANSACTION;
SELECT COUNT(*) FROM booking
WHERE from_datetime = '2019-01-01 12:00:00' AND to_datetime = '2019-01-01 14:00:00'
FOR UPDATE;
-- If this returns zero count:
INSERT INTO booking VALUES ('2019-01-01 12:00:00', '2019-01-01 14:00:00');
COMMIT;

The FOR UPDATE option in the SELECT causes MySQL to lock the appropriate part of the table. If another user executes the same code, they'll be blocked if they try to select the same times.

Locking tables is not such a good idea in some cases.

You should use a Transaction and check in your transaction if the ranges overlap.

Check overlap of date ranges in MySQL

https://dev.mysql.com/doc/refman/8.0/en/commit.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM