1

I am getting

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();
4

3 回答 3

2

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

于 2012-06-14T09:20:15.513 回答
1

您测试您的查询是否以大写 SELECT 开头,但事实并非如此。因此,您的两个查询被添加到批处理语句中。你可以使用

com.mysql.jdbc.StringUtils.startsWithIgnoreCase(results[i], "select");
于 2012-06-14T09:23:20.223 回答
0

确保PreparedStatement#executeBatch()在使用批次时使用。

还要确保你执行

int n = preparedStatement.executeUpdate();
于 2012-06-14T09:21:41.430 回答