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(); 获取刚插入的那个自动自增字段的值。
测试代码:
@Test public void testNextValue() { try { String MySQL = "jdbc:mysql://localhost/hibernate"; Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection conn = DriverManager.getConnection(MySQL, "root", "root"); String sql = "insert into testnotnull values(null, ?, ?)"; java.sql.PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); conn.setAutoCommit(false); int i = 1; pstmt.setInt(i++, 234); pstmt.setString(i++, "sdfsdf"); pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); System.out.println("The value is "); if(rs.next()) { System.out.println(rs.getInt(1)); } conn.commit(); conn.setAutoCommit(true); } catch (Exception e) { e.printStackTrace(); } finally { //do close.... } }
如果只是单纯的想要获取Auto_increment的最大值,可用
select max(id) from testnotnull;
或 show table status from hibernate like 'testnotnull';获取其中的Auto_increment的值。
这两种方法都不是线程安全的!!!!!