0

I want to get the last inserted ID as long. Because the primary key of my table is of long data type.

Here's my code:

        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();
        }

I've tested that when the maximum value of integer reaches I get last 1 as last inserted_id.

By the way, I've gone through this post.

Thanks.

Community
  • 1
  • 1
Anonymous One
  • 411
  • 2
  • 6
  • 16
  • `try (ResultSet generatedKeys = statement.getGeneratedKeys()) { generatedKeys.next(); SYstem.out.println(generatedKeys.getLong(1)); }` - By [BalusC](https://stackoverflow.com/users/157882/balusc) – Ferrybig Feb 23 '16 at 10:10

1 Answers1

2

try with the following code snippet:

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

Here's the full code:

        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();
        }
1000111
  • 13,169
  • 2
  • 28
  • 37