我有以下表结构
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 :(得分: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行。