Jedynym sposobem powrotu niektórych sterowników JDBC Statement.RETURN_GENERATED_KEYSjest wykonanie następujących czynności:
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);
}
Czy jest sposób, aby zrobić to samo PreparedStatement?
Edytować
Powód, dla którego zapytałem, czy mogę zrobić to samo, PreparedStatementrozważ następujący scenariusz:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
W USERtabeli znajduje się PRIMARY KEY (USER_ID)który to a BIGINT AUTOINCREMENT(dlatego nie widzisz go w SQL_CREATEString.
Teraz wypełniam plik ?using PreparedStatement.setXXXX(index, value). Chcę wrócić ResultSet rs = PreparedStatement.getGeneratedKeys(). Jak mogę to osiągnąć?
This method with argument cannot be called on a PreparedStatement or CallableStatement.Dokument Java mówi, że oznacza to, że musimy używać funkcji executeUpdate () bez argumentów, mimo żeexecuteUpdate(arg)metoda może być dziedziczona w klasie PreparedStatement, ale nie musimy jej używać, w przeciwnym razie otrzymamy SQLException.