Jack Harkness
Jack Harkness

Reputation: 810

How can I get auto generated keys and set the resultset type?

I have this SQL statement:

con = cpds.getConnection();
            con.setAutoCommit(false);
            SQL = "INSERT INTO person(accountID,addressID,lastName,firstName,middleName,suffix,gender,birthDate, [language], ethinicity) "
                    + "VALUES(?,?,?,?,?,?,?,?,?,?)";
            PreparedStatement stmt = con.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

What I want to be able to do is get the generated keys for this statement. Now I have done this before, but without setting the resultset typescroll parameter. It seems that there is no argument that does this either:

PreparedStatement stmt = con.prepareStatement(SQL,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY, Statement.RETURN_GENERATED_KEYS)

What I want to know is this: How can I set the resultset type to typescroll insensitive AND get generated keys?

Upvotes: 4

Views: 4117

Answers (2)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Statement#getGeneratedKeys() returns a ResultSet that you can use to retrieve the keys as

ResultSet rsKeys = statement.getGeneratedKeys();
if (rsKeys.next()) {
    person.setId(rsKeys.getLong(1));
}

How can I set the resultset type to typescroll insensitive AND get generated keys?

Doing this doesn't make sense because you can expect to retrieve keys only after doing an insert. While you would want to set the scroll type only for a resultset i.e. after a query. So, the two things are mutually exclusive and hence the API obviously doesn't support it.

Upvotes: 5

Jigar Joshi
Jigar Joshi

Reputation: 240938

statement.getGeneratedKeys(); would help

Upvotes: 0

Related Questions