【问题标题】:Batch execution is not happening for deletion operation删除操作没有发生批量执行
【发布时间】:2018-01-30 20:34:47
【问题描述】:

我正在尝试从数据库中删除行作为批量更新操作。我已经编写了以下方法来完成任务,但是当我执行时,它不会从表中删除条目。所以表保持不变。 如果代码中有任何错误,请告诉我。

public void removeFromDb(String partnerId, List<String> packagedServiceIdList) throws CustomException {

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = getConnection();
        ps = con.prepareStatement(REMOVE_DATA_MAP);
        for(int i=0; i<packagedServiceIdList.size();i++) {

            ps.setString(1, partnerId);
            ps.setString(2, packagedServiceIdList.get(i));
            ps.addBatch();
            gLogger.debug("query is: "+ps.toString());
        }
        ps.executeUpdate();

    } catch (SQLException sqle) {
        gLogger.error("Exception while removing the record from table, SQLException:{}", sqle);
        throw new CustomException(feErrorEnum.INTERNAL_EXCEPTION, sqle.getMessage());
    } finally {
        closeConnection(con, ps, null);
    }
}

【问题讨论】:

    标签: java database jdbc


    【解决方案1】:

    你必须使用executeBatch()

    ps.executeBatch();
    

    而不是:

    ps.executeUpdate();
    

    注意executeBatch()

    返回 更新计数数组,其中包含每个命令的一个元素 批次。 数组的元素是根据 命令添加到批处理中的顺序。

    所以要检查你的批处理是否正常工作,你可以使用:

    int[] count = ps.executeBatch();
    

    你必须把你的批次放在

    con.setAutoCommit(false);//Disabling auto-commit mode
    
    ps = con.prepareStatement(REMOVE_DATA_MAP);
    for (int i = 0; i < packagedServiceIdList.size(); i++) {
    
        ps.setString(1, partnerId);
        ps.setString(2, packagedServiceIdList.get(i));
        ps.addBatch();
        gLogger.debug("query is: " + ps.toString());
    }
    
    int[] count = ps.executeBatch();//execute the batch
    
    con.commit();//Commit the SQL statements
    

    【讨论】:

    • 在我之前的代码中,我尝试使用 ps.executeBatch();。即使这样也没有用。
    • String REMOVE_CHANNEL_STATION_MAP = "从 channel_station_map 中删除合作伙伴 ID=?和 packaged_service_id=?";
    • partner_idpackaged_service_id是什么类型的?
    • 都是字符串。
    • 你确定我在你的代码中没有发现任何其他问题,但是你能告诉我你使用的是什么 rdbms 吗?
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 2015-01-16
    • 2015-02-15
    • 2016-03-14
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多