The only way that some JDBC drivers to return Statement.RETURN_GENERATED_KEYS
is to do something of the following:
long key = -1L;
Statement statement = connection.createStatement();
statement.executeUpdate(YOUR_SQL_HERE, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Is there a way to do the same with PreparedStatement
?
Edit
The reason I asked if I can do the same with PreparedStatement
consider the following scenario:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
In the USER
table there's a PRIMARY KEY (USER_ID)
which is a BIGINT AUTOINCREMENT
(hence why you don't see it in the SQL_CREATE
String.
Now, I populate the ?
using PreparedStatement.setXXXX(index, value)
. I want to return ResultSet rs = PreparedStatement.getGeneratedKeys()
. How can I achieve this?
This method with argument cannot be called on a PreparedStatement or CallableStatement.
It means we have to use executeUpdate() without argument even thoughexecuteUpdate(arg)
method can be inherited in PreparedStatement class but we don't have to use it otherwise we will get SQLException. – AmitG