gpt4 book ai didi

java - 准备语句根据记录中的另一个值更新一个值

转载 作者:行者123 更新时间:2023-11-29 21:25:27 24 4
gpt4 key购买 nike

我有下面的表格结构

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

以上只是一个例子;然而我真正的 table 看起来只是这样。根据 msg 字段的值,我需要调用一个 API,该 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();
}
}
}

最佳答案

惯用的 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行。

关于java - 准备语句根据记录中的另一个值更新一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com