繁体   English   中英

PreparedStatement根据记录中的另一个值更新一个值

[英]PreparedStatement to update one value based on another in a record

我有下面的表结构

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

以上只是一个例子; 但是我的真实桌子看起来就像那样。 基于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行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM