MySQL获取Auto_increment字段刚插入的值

来源:互联网 发布:苹果6淘宝 编辑:程序博客网 时间:2024/05/17 08:41

MySQL获取Auto_increment字段刚插入的值

不能使用select max(id) from testnotnull;

这样来获取刚插入的那个递增字段的值,

这样没有考虑多线程。

 

一个比较好的方法是:

使用java.sql.PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

在插入数据之后,即执行pstmt.executeUpdate()后,

ResultSet rs = pstmt.getGeneratedKeys(); 获取刚插入的那个自动自增字段的值。

测试代码:

 

如果只是单纯的想要获取Auto_increment的最大值,可用

select max(id) from testnotnull;

或 show table status from hibernate like 'testnotnull';获取其中的Auto_increment的值。

这两种方法都不是线程安全的!!!!!

 

原创粉丝点击