java - java.sql.SQLException "database in auto-commit mode"的原因

标签 java sqlite transactions

我在 servlet 应用程序中使用 sqlite 数据库和 java.sql 类将一些数据批量插入数据库。 连续插入了四次不同类型的数据。 每一个看起来像这样:

PreparedStatement statement = conn
    .prepareStatement("insert or ignore into nodes(name,jid,available,reachable,responsive) values(?,?,?,?,?);");
for (NodeInfo n : nodes)
{
    statement.setString(1, n.name);
    statement.setString(2, n.jid);
    statement.setBoolean(3, n.available);
    statement.setBoolean(4, n.reachable);
    statement.setBoolean(5, n.responsive);
    statement.addBatch();
}

conn.setAutoCommit(false);
statement.executeBatch();
conn.commit();
conn.setAutoCommit(true);
statement.close();

但有时我会得到

java.sql.SQLException: database in auto-commit mode

我在 java.sql.Connection 的源代码中发现,当数据库处于自动提交模式时调用 commit() 时会抛出此异常。但是我之前关闭了自动提交,我看不到一些与并行执行相关的问题的任何地方,因为现在应用程序只打开了一次。

你知道如何调试这个问题吗?也许这个错误还有其他原因(因为我刚刚发现在将 null 插入非空字段时会抛出有关数据库未找到或未正确配置的异常)?。

最佳答案

可能是语句的顺序的问题。您的数据库语句应该是:

  PreparedStatement statement1 = null;
  PreparedStatement statement2 = null;
  Connection connection=null;

    try {
        //1. Obtain connection and set `false` to autoCommit
        connection.setAutoCommit(false);
        //2. Prepare and execute statements
        statement1=connection.prepareStatement(sql1);
        statement2=connection.prepareStatement(sql2);
        ...
        //3. Execute the statements

        statement1.executeUpdate();
        statement2.executeUpdate();

        //4. Commit the changes

        connection.commit();
        }
    } catch (SQLException e ) {
        if (connection!=null) {
            try {
                connection.rollback();
            } catch(SQLException excep) {}
        }
    }finally {
        if (statement1 != null) {
            statement1.close();
        }
        if (statement2 != null) {
            statement2.close();
        }
       if(connection != null){
          connection.setAutoCommit(true);
          connection.close();
        }
   }

关于java - java.sql.SQLException "database in auto-commit mode"的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194972/

相关文章:

java - JSP 页面缓存结果的最佳实践?

Java IO 给我一个错误

java - 当我将 recyclerview 版本从 23.0.1 更改为 23.2.1 时,gradle 文件错误

java - 删除 Android SQLite 数据库中的行后行 ID 错误

c# - 处理器架构与 SQLite Nuget 包和任何 CPU Web 项目不匹配

android - 房间线程管理

java - OrmLite:Dao.callBatchTasks() 和 TransactionManager.callInTransaction() 之间的区别

java - Spring 启动 : save to repository doesnt work with @Transactional(propagation = Propagation. REQUIRES_NEW)

database - 如何协调文件系统和数据库?

java - 运行 gradle 构建时出错