[rt-users] Getting the Primary Key after an insert

Rick Edwards ricke at mjr.com
Fri Mar 28 07:59:34 EST 2003


Hong,

This is probably a JDBC 3.0 feature:

// Assuming you've got a statement to execute
//
int res = myStmt.executeUpdate();
ResultSet rs = myStmt.getGeneratedKeys();
boolean isKeyAvailable = rs.next();
if( isKeyAvailable ) {
	int key = rs.getInt(1); // Assuming the key is an int
}
// Blah blah blah
//

If your app is the only one that'll be accessing this table you can just put 
the code into a synchronized method and to a 'select MAX(foo.key) from foo;' 
to get the new key. Ugly, but it works.

Rick



More information about the rt-users mailing list