使用Java根据数据库中的最大ID生成下一个ID [英] Generate next Id as per the max id in database using Java

查看:487
本文介绍了使用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

这篇关于使用Java根据数据库中的最大ID生成下一个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆