2014-12-03 90 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;