选择"进行更新"用JDBC?

时间:2017-10-28 22:34:49

标签: java postgresql jdbc select-for-update

我想使用JDBC在Java中创建for update select语句,但不确定如何完成。

如果您不熟悉更新,可以在此处阅读 https://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE

例如,我有以下选择语句

我的选择陈述

select email from email_accounts where already_linked = false order by random() limit 1

我的更新声明

UPDATE email_accounts set already_linked = true, account_link_timestamp = now() where email = ?

在使用for update时使用JDBC如何在Java中完成?

1 个答案:

答案 0 :(得分:6)

首先将for update添加到您的选择(以及您要更新的其他列),然后更新它们。另外,如评论中所述,请确保getConnection在没有自动提交的情况下返回Connection。您需要为滚动和Statement设置CONCUR_UPDATABLE类型。像,

String[] colNames = { "email", "already_linked", "account_link_timestamp" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
        + "from email_accounts where already_linked = false for update";
try (Connection conn = getConnection(); // Make sure conn.setAutoCommit(false);
        Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
                ResultSet.CONCUR_UPDATABLE);
        ResultSet rs = stmt.executeQuery(query)) {
    while (rs.next()) {
        // Get the current values, if you need them.
        String email = rs.getString(colNames[0]);
        boolean linked = rs.getBoolean(colNames[1]);
        Timestamp time = rs.getTimestamp(colNames[2]);
        // ...
        rs.updateBoolean(colNames[1], true);
        rs.updateTimestamp(colNames[2], //
                new Timestamp(System.currentTimeMillis()));
        rs.updateRow();
    }
} catch (SQLException e) {
    e.printStackTrace();
}