View RSS Feed

My Java Tips

Retrieving auto generated key (JDBC 3.0)

Rate this Entry
by , 11-28-2011 at 06:41 PM (3000 Views)
JDBC 3.0 introduces a lot of interesting and exciting features which makes database programming simpler. 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:

Java Code:
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);
}

Submit "Retrieving auto generated key (JDBC 3.0)" to Facebook Submit "Retrieving auto generated key (JDBC 3.0)" to Digg Submit "Retrieving auto generated key (JDBC 3.0)" to del.icio.us Submit "Retrieving auto generated key (JDBC 3.0)" to StumbleUpon Submit "Retrieving auto generated key (JDBC 3.0)" to Google

Categories
JDBC

Comments