Retrieving auto generated key (JDBC 3.0)

19 April 2008

JDBC 3.0 introduces a lot of interesting and exciting features which makes database programming simplier. In this post, I will address how to retrieve auto generated keys using JDBC 3.0.

To get the key, simply specify in the statement’s execute() method an optional flag denoting that you are interested in the generated value. Flags of your interest are: Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS. Execute the statement and now you can obtain the values of the generated keysby retrieving a ResultSet from a Statement’s instance method, getGeneratedKeys(). Now the ResultSet contains a row for each generated key.

Time for an example:

Statement stmt = conn.createStatement();
// Obtain the generated key that results from the query.
stmt.executeUpdate("INSERT INTO authors " +
                   "(first_name, last_name) " +
                   "VALUES ('George', 'Orwell')",
                   Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if ( rs.next() ) {
    // Retrieve the auto generated key(s).
    int key = rs.getInt(1);
}

del.icio.us:Retrieving auto generated key (JDBC 3.0)  digg:Retrieving auto generated key (JDBC 3.0)  spurl:Retrieving auto generated key (JDBC 3.0)  wists:Retrieving auto generated key (JDBC 3.0)  simpy:Retrieving auto generated key (JDBC 3.0)  newsvine:Retrieving auto generated key (JDBC 3.0)  blinklist:Retrieving auto generated key (JDBC 3.0)  furl:Retrieving auto generated key (JDBC 3.0)  reddit:Retrieving auto generated key (JDBC 3.0)  fark:Retrieving auto generated key (JDBC 3.0)  blogmarks:Retrieving auto generated key (JDBC 3.0)  Y!:Retrieving auto generated key (JDBC 3.0)  smarking:Retrieving auto generated key (JDBC 3.0)  magnolia:Retrieving auto generated key (JDBC 3.0)  segnalo:Retrieving auto generated key (JDBC 3.0)  gifttagging:Retrieving auto generated key (JDBC 3.0)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Retrieving auto generated key (JDBC 3.0)

Leave a Reply