2017-10-28 113 views
0

我想使用JDBC在Java中創建一個for update select語句,但不確定它將如何完成。用JDBC選擇「for update」?

如果你不熟悉的更新,你可以讀到這裏 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 = ? 

如何在使用JDBC的Java中使用for update執行此操作?

回答

3

您首先將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(); 
} 
+1

'conn.setAutoCommit = false'是'for update'鎖有效的必要條件,還是沒有關係? –

+1

另外,'createStatement'不需要用'ResultSet.CONCUR_UPDATABLE'來調用,所以'updateRow'可以工作嗎? –

+0

@GordThompson很好,謝謝。是啊。這是晚餐時間,我有點匆忙。 –