java - 删除操作未发生批量执行

标签 java database jdbc

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

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

最佳答案

您必须使用executeBatch()

ps.executeBatch();

而不是:

ps.executeUpdate();

注意 executeBatch():

Returns an array of update counts containing one element for each command in the batch. The elements of the array are ordered according to the order in which commands were added to the batch.

因此,要检查您的批处理是否正常工作,您可以使用:

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

关于java - 删除操作未发生批量执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530081/

相关文章:

java - 用于非数据库结构的 JDBC 模拟器

java - 检查当前用户是否有权访问数据库

Java 重写方法丢弃异常

java - 从代码渲染一个 jsp 页面并将渲染后的 html 输出作为字符串

java - H2 的嵌入式数据库在哪里存储数据?

mysql - 使用 Hadoop 作为 MySQL 存储引擎?

java - 从 Java 应用程序启动进程

java - 如何在java中给出FTP地址?

python - 如果一列大于另一列则删除行

mysql - 在 JSP 上显示自动生成的主键