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

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值