2016-02-21 90 views
0

我有下面的表結構PreparedStatement的更新在記錄中根據另外一個值

id msg keyword 
----------------- 
1 abc ? 
2 xyz ? 

上面的僅僅是一個例子;但是我真正的桌子只是這樣。根據msg字段的值,我需要調用API來計算msg中的關鍵字,然後更新特定的記錄。我怎樣才能獲得記錄和更新,同時使用Java PreparedStatement? 也因爲我的數據庫非常大,那麼執行它的有效方法是什麼?下面的代碼片段:

public void updateColumns() { 
     try { 
      PreparedStatement stmt = null; 
      ResultSet resultSet = null; 
      String query = "select * from '" + Constants.tableName + "'"; 

      // How to uypdate the record here by calling my custom API that reads the msg and returns the keywords in the message?? 
      stmt = conn.prepareStatement(query); 

      stmt.execute(); 
      stmt.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       conn.close(); 
      } catch (SQLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

回答

0

慣用JDBC的解決辦法是生成一個批處理更新:

String select = "SELECT id, msg FROM my_table"; 
String update = "UPDATE my_table SET keyword = ? WHERE id = ?"; 
try (Statement stmt = conn.createStatement(); 
    ResultSet rs = stmt.executeQuery(select); 
    PreparedStatement ps = conn.prepareStatement(update);) { 
    while (rs.next()) { 
     ps.setInt(1, rs.getInt(1)); 
     ps.setString(2, MyAPI.calculateKeyword(rs.getString(2)); 
     ps.addBatch(); 
    } 
    ps.executeBatch(); 
} 

當然,如果你的表是非常大的,你可能要考慮每x行。

+0

感謝您的回覆。如果我需要批量執行此操作,我需要設置批量大小。由於我必須同時執行兩個查詢,批處理是否能夠在同一批記錄中執行這兩個查詢?在上述代碼片段中:{ } ps.setString(2,MyAPI.calculateKeyword(rs.getString(2));} 如果它不是 { ps.setInt(2,rs.getInt(2)); ps.setString(1, MyAPI.calculateKeyword(rs.getString(1)); } – user5917011

相關問題