本文介绍了带有Statement.RETURN_GENERATED_KEYS的PreparedStatement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些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做同样的事情

修改

我问我是否可以用 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.

现在,我使用<$ c $填充 c> 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?

推荐答案

您可以使用 prepareStatement 方法获取额外的 int 参数

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 08:48