2016-02-23 123 views
0

我想獲取最後插入的ID爲long。因爲我的表的主鍵是long數據類型。如何在java中獲取最後插入的ID mysql mysql

這裏是我的代碼:

 Connection connection = null; 
     Statement statement = null; 
     try { 
      String sql = "INSERT INTO testTable(name) VALUES('Anonym')"; 
      connection = DriverManager.getConnection(DB_URL, USER, PASS); 
      statement = connection.createStatement(); 
      long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); 
      System.out.println("LAST INSERTED ID = "+lastInsertedID); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

我測試過,當整數的最大值達到我拿到最後1個去年inserted_id。

順便說一下,我已經通過這post

謝謝。

+0

'嘗試(結果集generatedKeys =的Statement.getGeneratedKeys()){generatedKeys.next();的System.out.println(generatedKeys.getLong(1)); '' - [BalusC](https://stackoverflow.com/users/157882/balusc) – Ferrybig

回答

1

嘗試用下面的代碼片斷:

ResultSet rs= statement.getGeneratedKeys(); 
if (rs.next()) 
{ 
    System.out.println("Last Inserted ID = "+rs.getLong(1)); 
} 

下面是完整的代碼:

 Connection connection = null; 
     Statement statement = null; 
     try { 
      String sql = "INSERT INTO testTable(name) VALUES('Anonym')"; 
      connection = DriverManager.getConnection(DB_URL, USER, PASS); 
      statement = connection.createStatement(); 
      long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); 
      ResultSet rs= statement.getGeneratedKeys(); 
      if (rs.next()) 
      { 
       System.out.println("Last Inserted ID = "+rs.getLong(1)); 
      }  

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
相關問題