mysql 插入数据后返回当前的自增ID方法

存储过程的写法:

mysql>create procedure test(

->in username varchar(50),

->in password varchar(50),

->out userid int)

->begin

->set @sql=concat("insert into user(`username`,`password`) values(' ",username,"' ,' ",password,"' )");

->prepare stmt from @sql;

->execute stmt;

->select @@identity into userid;

->end ||

调用:

mysql>call test('name','pwd',@id);

mysql>select @id;

其中的prepare和execute使用请参考手册

 

 

 

我们在写数据库程序的时候,经常会需要获取某个表中的最大序号数,

一般情况下获取刚插入的数据的id,使用select max(id) from table 是可以的。
但在多线程情况下,就不行了。

下面介绍三种方法

(1)getGeneratedKeys()方法:

程序片断:

Connection conn = ;
Serializable ret = null;
PreparedStatement state = .;
ResultSet rs=null;
try {
state.executeUpdate();
rs = state.getGeneratedKeys();
if (rs.next()) {
ret = (Serializable) rs.getObject(1);
}
} catch (SQLException e) {
}
return ret;

(2)LAST_INSERT_ID:

select LAST_INSERT_ID();

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

在多用户交替插入数据的情况下max(id)显然不能用。
这就该使用LAST_INSERT_ID了,因为LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的 Connection对象,LAST_INSERT_ID函数将返回该Connection对AUTO_INCREMENT列最新的insert or update*作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。使用单INSERT语句插入多条记录, LAST_INSERT_ID返回一个列表。

(3)select @@IDENTITY:

String sql="select @@IDENTITY";

@@identity是表示的是最近一次向具有identity属性(即自增列)的表插入数据时对应的自增列的值,是系统定义的全局变量。一般系统定义的 全局变量都是以@@开头,用户自定义变量以@开头。比如有个表A,它的自增列是id,当向A表插入一行数据后,如果插入数据后自增列的值自动增加至 101,则通过select @@identity得到的值就是101。使用@@identity的前提是在进行insert操作后,执行select @@identity的时候连接没有关闭,否则得到的将是NULL值。

posted @ 2015-05-11 00:24  Tim&Blog  阅读(2127)  评论(0编辑  收藏  举报