主キーを取得する正しい方法は、getGeneratedKeys
を使用することです。 ファシリティ(Statement.RETURN_GENERATED_KEYS
を使用してアクティブ化できます Statement.execute*
のいずれかを含む値 またはConnection.prepareStatement
メソッド。
ほとんどのデータベースでは、これを使用して主キーを直接取得できます。ただし、Oracleの場合、これによりROWID
を取得できます。 、このROWID
挿入された行をテーブルに照会し、主キーを取得するために使用できます。
例:
stmt.executeUpdate("INSERT INTO theTable(column1) VALUES ('a')",
Statement.RETURN_GENERATED_KEYS);
ResultSet keys = stmt.getGeneratedKeys();
int primaryKey = -1;
if (keys.next()) {
try (PreparedStatement keyStatement =
connection.prepareStatement("SELECT ID FROM theTable WHERE ROWID = ?")) {
keyStatement.setRowId(keys.getRowId(1));
try (ResultSet rs = keyStatement.executeQuery()) {
primaryKey = rs.getInt(1);
}
}
}