带有Statement.RETURN_GENERATED_KEYS的PreparedStatement

时间:2010-11-19 10:47:40

标签: java jdbc

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

有没有办法对PreparedStatement执行相同操作?


修改

我问我是否可以对PreparedStatement执行相同操作的原因考虑以下情况:

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字符串中看不到它。

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

5 个答案:

答案 0 :(得分:128)

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

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

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

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

答案 1 :(得分:62)

你的意思是这样的?

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

答案 2 :(得分:9)

我现在没有编译器,我会回答一个问题:

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

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

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

PreparedStatementStatement的子接口,所以我没有看到为什么这不起作用的原因,除非有些JDBC驱动程序有问题。

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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