代码之家  ›  专栏  ›  技术社区  ›  Arya

使用JDBC选择“for update”?

  •  2
  • Arya  · 技术社区  · 8 年前

    我想创建一个 for update 使用JDBC在Java中选择语句,但不确定如何执行。

    https://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE

    例如,我有以下select语句

    我的select语句

    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 = ?
    

    在Java中,使用JDBC和 用于更新 ?

    1 回复  |  直到 7 年前
        1
  •  11
  •   Gord Thompson    8 年前

    您首先添加 for update 选择(以及要更新的其他列),然后更新它们。此外,如评论中所述,请确保您的 getConnection 返回a 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();
    }