Menu

#141 Statement.getGeneratedKeys() doesn't work when the Statement (PreparedStatement) was executed using executeUpdate()

open
nobody
None
5
2012-03-31
2012-03-31
Jira Trac
No

For my integration tests, I have a table with an AUTO_INCREMENT column:

{code}
CREATE TABLE t_triggers (
id_generated int AUTO_INCREMENT not null,
id int null,
counter int null,

CONSTRAINT pk_t_triggers PRIMARY KEY (id_generated)
)
{code}

Now, when I insert records to the above table, I'd like to fetch the generated values for id_generated using JDBC's Statement.getGeneratedKeys(), as documented here:
http://www.cubrid.org/manual/841/en/Getting%20Auto-Increment%20Column%20Values

I'm using this logic which doesn't work (i.e. the returned result sets rs1 and rs2 are empty / invalid):
{code}
Connection connection = create().getConnection();
PreparedStatement s1 = connection.prepareStatement(
insert into t_triggers (counter) values (0),
Statement.RETURN_GENERATED_KEYS);
s1.executeUpdate();
ResultSet rs1 = s1.getGeneratedKeys();
while (rs1.next()) {
System.out.println(rs1.getObject(1));
}

Statement s2 = connection.createStatement();
s2.executeUpdate(
insert into t_triggers (counter) values (0),
Statement.RETURN_GENERATED_KEYS);
ResultSet rs2 = s2.getGeneratedKeys();
while (rs2.next()) {
System.out.println(rs2.getObject(1));
}
{code}

I have noticed, that the issue appears only when using executeUpdate(). When I use execute() (as documented in the CUBRID manual), the result sets return the expected values:

{code}
Connection connection = create().getConnection();
PreparedStatement s1 = connection.prepareStatement(
insert into t_triggers (counter) values (0),
Statement.RETURN_GENERATED_KEYS);
s1.execute();
ResultSet rs1 = s1.getGeneratedKeys();
while (rs1.next()) {
System.out.println(rs1.getObject(1));
}

Statement s2 = connection.createStatement();
s2.execute(
insert into t_triggers (counter) values (0),
Statement.RETURN_GENERATED_KEYS);
ResultSet rs2 = s2.getGeneratedKeys();
while (rs2.next()) {
System.out.println(rs2.getObject(1));
}
{code}

The above prints:
1
2

Discussion

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.