返回的一些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);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做同样的事情PreparedStatement?
编辑
我问我是否可以这样做的原因PreparedStatement考虑以下情况:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
Run Code Online (Sandbox Code Playgroud)
在USER表中有一个PRIMARY KEY (USER_ID)是BIGINT AUTOINCREMENT(因此你没有在SQL_CREATE字符串中看到它.
现在,我填充?使用PreparedStatement.setXXXX(index, value).我想回来ResultSet rs = PreparedStatement.getGeneratedKeys().我怎样才能做到这一点?