简体   繁体   中英

What is wrong with this getGeneratedKeys() JDBC statement?

This code fragment

PreparedStatement statement = connect.prepareStatement(
          query, Statement.RETURN_GENERATED_KEYS);
statement.executeUpdate(query);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
    ...
}

keeps throwing

java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().

I'd say that generatedkeys ARE requested at creation of the statement, but apparently I'm wrong. What is the issue here? (I'm new to JDBC. What I'm trying to do is retrieving the primary key value which has been automatically set (AUTO_INCREMENTed) during the preceding record insertion. Maybe there is a better way to do that... I'm using mysql.)

Your problem is this line:

statement.executeUpdate(query);

don't pass the query parameter in use the no parameter version:

statement.executeUpdate();

The first version doesn't use the prepared statement you already made but instead makes a new one using your query String (without the RETURN_GENERATED_KEYS option)

Remove the parameter from

statement.executeUpdate(query);

change to

 statement.executeUpdate();

because you have already prepared the statement in

PreparedStatement statement = connect.prepareStatement(
          query, Statement.RETURN_GENERATED_KEYS);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM