Java 带有 Statement.RETURN_GENERATED_KEYS 的 PreparedStatement

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4224228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:46:08  来源:igfitidea点击:

PreparedStatement with Statement.RETURN_GENERATED_KEYS

javajdbc

提问by Buhake Sindi

The only way that some JDBC drivers to return Statement.RETURN_GENERATED_KEYSis to do something of the following:

某些 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);
}

Is there a way to do the same with PreparedStatement?

有没有办法对它做同样的事情PreparedStatement



Edit

编辑

The reason I asked if I can do the same with PreparedStatementconsider the following scenario:

我问我是否可以PreparedStatement考虑以下情况的原因:

private static final String SQL_CREATE = 
            "INSERT INTO
            USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB) 
            VALUES (?, ?, ?, ?, ?)";

In the USERtable there's a PRIMARY KEY (USER_ID)which is a BIGINT AUTOINCREMENT(hence why you don't see it in the SQL_CREATEString.

USER表中有一个PRIMARY KEY (USER_ID)which 是一个BIGINT AUTOINCREMENT(因此您在SQL_CREATEString.

Now, I populate the ?using PreparedStatement.setXXXX(index, value). I want to return ResultSet rs = PreparedStatement.getGeneratedKeys(). How can I achieve this?

现在,我填充?using PreparedStatement.setXXXX(index, value)。我想回来ResultSet rs = PreparedStatement.getGeneratedKeys()。我怎样才能做到这一点?

采纳答案by J?rn Horstmann

You can either use the prepareStatementmethod taking an additional intparameter

您可以使用prepareStatement带有附加int参数的方法

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

对于某些 JDBC 驱动程序(例如 Oracle),您必须明确列出生成的键的列名或索引:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

回答by darioo

Not having a compiler by me right now, I'll answer by asking a question:

我现在没有编译器,我会通过提问来回答:

Have you tried this? Does it work?

你试过这个吗?它有效吗?

long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
    key = rs.getLong(1);
}

Disclaimer: Obviously, I haven't compiled this, but you get the idea.

免责声明:显然,我还没有编译这个,但你明白了。

PreparedStatementis a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.

PreparedStatementStatement 的一个子接口,所以我看不出这不起作用的原因,除非某些 JDBC 驱动程序有问题。

回答by nanda

You mean something like this?

你的意思是这样的?

long key = -1L;

PreparedStatement preparedStatement = connection.prepareStatement(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setXXX(index, VALUE);
preparedStatement.executeUpdate();

ResultSet rs = preparedStatement.getGeneratedKeys();

if (rs.next()) {
    key = rs.getLong(1);
}

回答by niraj

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        ps.execute();
        generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
            driveDetail.setStopDuration(generatedKeys.getInt(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("Error inserting into alarm_event : {}", e
                .getMessage());
        logger.info(ps.toString());
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e
                        .getMessage());
            }
        }
    }
    JDatabaseManager.freeConnection(conn);
}

回答by Dharmendrasinh Chudasama

String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);

preparedStatement.setXXX(1, VALUE); 
preparedStatement.setXXX(2, VALUE); 
....
preparedStatement.executeUpdate();  

ResultSet rs = preparedStatement.getGeneratedKeys();  
int key = rs.next() ? rs.getInt(1) : 0;

if(key!=0){
    System.out.println("Generated key="+key);
}