带有 Statement.RETURN_GENERATED_KEYS 的 PreparedStatement [英] PreparedStatement with Statement.RETURN_GENERATED_KEYS
问题描述
某些 JDBC 驱动程序返回 Statement.RETURN_GENERATED_KEYS
的唯一方法是执行以下操作:
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);
}
有没有办法对 PreparedStatement
做同样的事情?
Is there a way to do the same with PreparedStatement
?
编辑
我问我是否可以用 PreparedStatement
做同样的事情的原因考虑以下场景:
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 (?, ?, ?, ?, ?)";
在 USER
表中有一个 PRIMARY KEY (USER_ID)
,它是一个 BIGINT AUTOINCREMENT
(因此你在SQL_CREATE
字符串.
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.
现在,我使用 PreparedStatement.setXXXX(index, value)
填充 ?
.我想返回 ResultSet rs = PreparedStatement.getGeneratedKeys()
.我怎样才能做到这一点?
Now, I populate the ?
using PreparedStatement.setXXXX(index, value)
. I want to return ResultSet rs = PreparedStatement.getGeneratedKeys()
. How can I achieve this?
推荐答案
您可以使用带有附加 int
参数的 prepareStatement
方法
You can either use the prepareStatement
method taking an additional int
parameter
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
对于某些 JDBC 驱动程序(例如 Oracle),您必须明确列出生成的键的列名或索引:
For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:
PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})
这篇关于带有 Statement.RETURN_GENERATED_KEYS 的 PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!