2014-12-03 240 views
0

使用表中的代码插入记录,其中一个字段是自动增加的(id)。我如何才能找出我刚刚插入的记录中autoincremented字段(id)的价值?了解自动增量字段的值

  PreparedStatement ps = null; 
    Connection con = null; 
    ResultSet rs = null; 
    int rows = 0; 
    try { 
     String SQL_DRV = "org.hsqldb.jdbcDriver"; 
     String SQL_URL = "jdbc:hsqldb:hsql://localhost/localDB"; 

        Class.forName(SQL_DRV); 
     con = DriverManager.getConnection(SQL_URL, "sa", ""); 

           ps = con.prepareStatement(
       "insert into infousuarios (nombre, apellidos, email) " + 
       "values (?, ?, ?)"); 
     ps.setString(1, name); 
     ps.setString(2, surnames); 
     ps.setString(3, login+"@micorreo.com"); 


     rows = ps.executeUpdate(); 
     // How I can know the value of autoincrement field (id) of the record just enter?? 
+0

大多数数据库有一个函数来获取它,平时像“最后插入身份证”或者这样的。 – Erik 2014-12-03 12:07:44

+0

看这个答案http://stackoverflow.com/questions/10353405/how-to-return-last-inserted-auto-incremented-row-id-in-hsql – 2014-12-03 12:11:59

+0

已解决。谢谢@SemyonSadetsky – user3764379 2014-12-03 12:25:38

回答

0

使用getGeneratedKeys()

ps = con.prepareStatement(
     "insert into infousuarios (nombre, apellidos, email) " + 
     "values (?, ?, ?)", Statement.RETURN_GENERATED_KEYS); 

ps.setString(1, name); 
ps.setString(2, surnames); 
ps.setString(3, login+"@micorreo.com"); 

rows = ps.executeUpdate(); 

ResultSet keys = ps.getGeneratedKeys(); 
long id = -1; 

if (keys.next()) { 
    id = rs.getLong(1); 
} 

注意调用prepareStatement通过PreparedStatement.RETURN_GENERATED_KEYS,并调用ps.getGeneratedKeys()

0

INSERT_ID可以检索最后插入的ID 的$ id = $ mysqli-> INSERT_ID;