这是我从文件中读取 SQL 然后进行批量更新的代码
public void update(Connection conn, File f) {
Statement st = null;
Scanner sc = null;
try {
conn.setAutoCommit(false);
st = conn.createStatement();
//Scann the file line by line and addBatch each line...
st.executeBatch();
conn.commit();
/************************/
conn.setAutoCommit(true);
/************************/
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (st != null) { st.close();}
if (conn != null) { conn.close(); }
} catch (Exception e) {
e.printStackTrace();
}
}
}
我尝试过的数据库:HSQLDB(进程内模式)
、HSQLDB(内存模式)
、MySQL
我尝试过的数据库池:No Pooling(DriverManger)
、DBCP
、BoneCP
我的应用程序按以下顺序运行:
1. one batchUpdate() to execute many "create table" and "insert" SQL statement
2. many executeQuery() to execute many "select" SQL statement
3. one batchUpdate() to execute many "drop table" statement
几乎所有数据库和数据库池的组合都可以在没有我在代码中突出显示的 conn.setAutoCommit(true);
的情况下完美运行,除了一个:BoneCP
+MySQL
。为了使这个组合发挥作用,我必须将 conn.setAutoCommit(true);
放在 update()
代码的末尾。否则,程序将在第三个进程(第二批更新)开始时挂起。
我的猜测是它挂起是因为它等待写锁
被释放,而我的第一个batchUpdate()
持有锁的唯一可能原因可能是是因为我将连接设置为不自动提交,导致 BoneCP 无法释放写锁
。所以我添加了 setAutCommit(true)
并且它起作用了。程序不再挂起。
所以我想问一下,我的猜测对吗?还是因为其他原因?它是否应该被视为一个错误,因为没有其他组合会产生这种奇怪的行为?谢谢。
最佳答案
BoneCP 有一个错误(在 0.8.0-rc3 中已修复),即自动提交未按照规范默认设置为 true。
您可以设置 config.setDefaultAutoCommit(true) 来解决该问题。
关于java - 组合使用 MySQL 和 BoneCP 时 jdbc executeBatch 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174600/