Reserving mySQL auto-incremented IDs?

♀尐吖头ヾ 提交于 2019-12-12 08:39:43

问题


We want to obtain an auto-increment ID from mySQL without actually storing it until the other non-mysql related processes are successfully completed, so that the entry is not stored if an exception or application crash happens. We need to use the ID as a key for the other processes. In essence we want to “reserve” the auto-increment and insert the rows into mySQL as the last step. We don’t want to insert any row until we know the entire process has completed successfully.

Is it possible to do this sort of auto-increment reservation in mySQL?

Note: I know about the SQL transactions. But our process contains non-SQL stuff that need to happen outside of the DB. These process may take few mins to several hours. But we don't want any other process using the same auto-increment ID. That is why we want a "reserve" an auto-increment ID without really inserting any data into the DB. –


回答1:


The only way to generate an auto-increment value is to attempt the insert. But you can roll back that transaction, and still read the id generated. In MySQL 5.1 and later, the default behavior is that auto-increment values aren't "returned" to the stack when you roll back.

START TRANSACTION;
INSERT INTO mytable () VALUES ();
ROLLBACK;
SELECT LAST_INSERT_ID() INTO @my_ai_value;

Now you can be sure that no other transaction will try to use that value, so you can use it in your external processes, and then finally insert a value manually that uses that id value (when you insert a specific id value, MySQL does not generate a new value).




回答2:


Have you considred using mysql tranactions?

The essense of it, you start a transaction, if all sql statements are correct and can be complteted, then you commit your transaction. If not, then you rollback as if nothing happened.

More details can be read in this link: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html




回答3:


you can use temporary table along with transaction

if transaction complete temp table will be gone and move data to real table

http://www.tutorialspoint.com/mysql/mysql-temporary-tables.htm



来源:https://stackoverflow.com/questions/18411384/reserving-mysql-auto-incremented-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!