java.sql.SQLException:批处理期间发生错误:必须执行或清除批处理 [英] java.sql.SQLException: error occurred during batching: batch must be either executed or cleared

查看:1303
本文介绍了java.sql.SQLException:批处理期间发生错误:必须执行或清除批处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在


java.sql.SQLException:批处理期间发生错误:批处理必须是
执行或清除

java.sql.SQLException: error occurred during batching: batch must be either executed or cleared

在下面的代码中。我想执行两个查询。

in the below code. I want to execute two queries.

String sql_query="insert into m_status values(20,'test');select * from m_user";
String query1 = sql_query.toUpperCase();

String[] results = query1.split(";");

stmt = conn1.createStatement();
conn1.setAutoCommit(false); 
for (int i = 0; i < results.length; i++) {
    if(results[i].startsWith("SELECT")) {
        rs1 = stmt.executeQuery(results[i]);
    }
    else if(results[i].startsWith("INSERT")){
        stmt.addBatch(results[i]);
    }
}
int [] updateCounts = stmt.executeBatch();
conn1.commit(); 
if (rs1 != null)
    rs1.close();
if (stmt != null)
    stmt.close();
if (conn1 != null)
    conn1.close();


推荐答案

使用两个语句,一个用于选择查询,另一个用于查询更新。 executeQuery 检查是否有批次为 Statament ,如果是,则抛出该错误。此外,将查询包装在 try-catch-finally 块中,并关闭finally块中的资源。实际上,您的代码可能会导致连接泄漏。

Use two statements, one for select queries and another one for updates. executeQuery checks if there batches for that Statament, and if so throws that error. Also, wrap your queries in a try-catch-finally block and close the resources in the finally block. As it is, your code could lead to connection leaks.

这篇关于java.sql.SQLException:批处理期间发生错误:必须执行或清除批处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆