我在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();
}
}
原文地址:https://codeday.me/bug/20190620/1248150.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。