Saturday, March 03, 2007

Return Auto Increment field from Informix Database

If you would like to get auto increment field in database after an INSERT statement, you may use Statement.getGeneratedKeys(), which returns an ResultSet in JDK 1.4 and above. You may need to check do your JDBC driver and database support it through DatabaseMetaData.supportsGetGeneratedKeys() method. For Informix Dynamic Server (IDS) it is only supported by its JDBC 3.00 driver and IDS 10 and later.

My production database is IDS version 9.4. Thus I can't use Statement.getGeneratedKeys(), and have to use vendor based solution: IfmxStatement.getSerial() which return int (Read here for more). Note that the return type of offical JDBC interface is ResultSet and IDS specific is int.

If your driver and/or database does not support both of the above, you can try this solution: Add a timestamp column with a unique index . Before you insert a new record, set its
timestamp to now. After inserting you can select the record by its timestamp and find out its
autogenerated key. If you like, you could then update the record by setting the timestamp to null. (suggestion by DrLaszloJamf in Sun Forum)