【问题标题】:java.sql.SQLException: error occurred during batching: batch must be either executed or clearedjava.sql.SQLException:批处理期间发生错误:必须执行或清除批处理
【发布时间】:2012-06-14 09:17:06
【问题描述】:

我来了

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

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

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

【问题讨论】:

    标签: java jakarta-ee jdbc


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      com.mysql.jdbc.StringUtils.startsWithIgnoreCase(results[i], "select");
      

      【讨论】:

        【解决方案3】:

        使用批处理时请务必使用PreparedStatement#executeBatch()。

        还要确保你执行

        int n = preparedStatement.executeUpdate();
        

        【讨论】:

          猜你喜欢
          • 2016-06-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-12
          • 2017-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多