nuo*_*eri 5 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();
Run Code Online (Sandbox Code Playgroud)
但是有时候我会
java.sql.SQLException: database in auto-commit mode
Run Code Online (Sandbox Code Playgroud)
我在源代码中发现,java.sql.Connection当commit()数据库处于自动提交模式时调用时会抛出此异常。但是我之前关闭了自动提交功能,我看不到任何与并行执行相关的问题,因为现在应用程序仅打开一次。
您知道如何调试此问题吗?也许还有其他原因导致此错误(因为我刚刚发现,将数据库插入null到非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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11877 次 |
| 最近记录: |