Reputation: 551
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.)
Upvotes: 1
Views: 1940
Reputation: 7919
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);
Upvotes: 3
Reputation: 31648
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)
Upvotes: 3