一部のJDBCドライバーが返す唯一の方法Statement.RETURN_GENERATED_KEYSは、次のことを行うことです。
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);
}
同じことをする方法はありPreparedStatementますか?
編集
私が同じことができるかどうか尋ねた理由はPreparedStatement、次のシナリオを考慮してください。
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
ではUSERテーブルがありますPRIMARY KEY (USER_ID)されているBIGINT AUTOINCREMENT(それゆえ、なぜあなたがそれを見ることはありませんSQL_CREATE文字列。
ここで、?usingを入力しPreparedStatement.setXXXX(index, value)ます。帰りたいですResultSet rs = PreparedStatement.getGeneratedKeys()。どうすればこれを達成できますか?
This method with argument cannot be called on a PreparedStatement or CallableStatement.と、executeUpdate(arg)メソッドはPreparedStatementクラスで継承できますが、引数なしでexecuteUpdate()を使用する必要がありますが、使用する必要はありません。そうしないと、SQLExceptionが発生します。