mysql - How to commit after multiple inserts
I have 2 cron processes running in parallel.
Process 1 does inserts and process 2 reads these inserts.
The problem I have is process 1 needs to insert multiple rows before process 2 can read them.
For example, 1. Process 1 needs to insert 10 rows
Process 1 inserts 3 rows
Process 2 reads these 3 rows
Process 1 inserts rows 4..10
Process 2 reads rows 4..10
What I needs is
Process 1 row inserts 1..10
Process 2 reads rows 1..10
A) Do I lock the table for the inserts in process 1?
B) Do I do a begin transaction, do inserts, and then commit?
开发者_开发问答If the table is locked will other session what for the unlock or will the other sessions get a lock error/warning?
Don't lock the table. Use a transaction. Transactions are atomic.
If you need to block process 2 until process 1 is complete, you should, as you suggested, lock the tables in question.
If you are inserted all 10 rows in a single query, you can rely on MyISAM table locking, however, if you are inserting using separate queries or are using InnoDB, you will want to explicitly lock the tables using [LOCK TABLES .. WRITE] (http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html) in process 1 and release the locks when you're finished.
Process 2 will then graciously wait for the write lock to be released before reading from the table.
It's very important here to ensure that the server receives the queries in process 1 first, so you may wish to use some magic there.
You could wrap the inserts inside of a transaction if you want to ensure that all of the inserts are atomically added, but you will still need to lock the table to solve the concurrency issue.
精彩评论