使用Java根据数据库中的最大ID生成下一个ID

使用Java根据数据库中的最大ID生成下一个ID

问题描述:

我正在开发Web应用程序.它将有多个用户.我正在使用mysql作为数据库.

I am working on a web application. It will have multiple users. I am using mysql as database.

在我的应用程序中,我正在获取最新的id (from the database, using max(id)),然后为新注册生成下一个ID.这种方法是不正确的,因为在我更新ID的时间之间ID可能会发生变化 然后我要求提供最新的身份证.我用Google搜索了,发现"last_insert_id()"

In my application i am fetching the latest id (from the database, using max(id)) , and then generating the next id for the new registration. This approach is incorrect, as the id might change between the time i update an id and i ask for the latest id. I googled up , and found "last_insert_id()"

但是,我尝试了"SELECT last_insert_id() FROM rdtype ",但它给出的记录数与0相同.

But, i tried "SELECT last_insert_id() FROM rdtype ", but its gives the same number of 0 as the no of records.

我应该如何进行?

您应将AUTO_INCREMENT属性用作ID. MySQL将在每次插入时处理递增的ID. AUTO_INCREMENT属性可用于为新行生成唯一标识.

You should use AUTO_INCREMENT attribute for id. MySQL will handle incrementing ID at each insert. The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows.

http://dev上查看MySQL参考.mysql.com/doc/refman/5.6/en/example-auto-increment.html