删除操作不会发生批量执行

时间:2018-01-30 20:34:48

标签: java database jdbc

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

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您必须使用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