您首先添加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();
}