9

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. –

4

3 回答 3

13

生成自动增量值的唯一方法是尝试插入。但是您可以回滚该事务,并仍然读取生成的 id。在 MySQL 5.1 及更高版本中,默认行为是当您回滚时自动增量值不会“返回”到堆栈中。

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

现在您可以确定没有其他事务会尝试使用该值,因此您可以在外部进程中使用它,然后最后手动插入一个使用该 id 值的值(当您插入特定的 id 值时,MySQL 不会产生一个新值)。

于 2013-08-23T20:49:52.830 回答
1

您可以将临时表与事务一起使用

如果事务完成临时表将消失并将数据移动到真实表

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

于 2013-08-23T20:48:31.917 回答
1

您是否考虑过使用 mysql 事务?

它的本质,你开始一个事务,如果所有的sql语句都正确并且可以完成,那么你就提交你的事务。如果没有,那么你就像什么都没发生一样回滚。

可以在此链接中阅读更多详细信息:http: //dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.html

于 2013-08-23T20:38:38.247 回答