Q:

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.)

A:

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)

