我在servlet应用程序中使用sqlite数据库和java.sql类将一些数据批量插入到数据库中.连续四次插入不同类型的数据.每个人看起来像这样:PreparedStatement statement = conn.prepareStatement(insert or ignore into ...
我在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.sql.SQLException“自动提交模式下的数据库”的原因
猜你喜欢
- SpringBoot中Tomcat和SpringMVC整合源码分析 2023-03-16
- 用于PL / SQL的ANTLR解析器,目标语言为Java 2023-11-02
- java解析多层嵌套json字符串问题 2023-06-06
- java.sql.SQLException: 流已被关闭 2023-11-04
- Java中二维数组的正确使用方法介绍 2023-07-15
- Java中双大括号初始化的理解与使用 2023-01-18
- SpringBoot实现动态配置及项目打包部署上线功能 2023-06-06
- 基于Java汇总Spock框架Mock静态资源经验 2022-10-24
- Hibernate识别数据库特有字段实例详解 2023-07-31
- 如何解决Webservice第一次访问特别慢的问题 2023-02-10