我正在编写一个分析 MySQL 数据库的应用程序,我需要同时执行几个 DML;例如:
// In ResultSet rsA: Select * from A;
rsA.beforeFirst();
while (rsA.next()) {
id = rsA.getInt("id");
// Retrieve data from table B: Select * from B where B.Id=" + id;
// Crunch some numbers using the data from B
// Close resultset B
}
我声明了一组数据对象,每个对象都有自己的数据库连接,而数据库又调用了几种数据分析方法。问题是所有线程都使用相同的连接,因此所有任务都抛出异常:“锁定等待超时;尝试重新启动事务”
我相信有一种方法可以编写代码,使任何给定的对象都有自己的连接并独立于任何其他对象执行所需的任务。例如:
DataObject dataObject[0] = new DataObject(id[0]);
DataObject dataObject[1] = new DataObject(id[1]);
DataObject dataObject[2] = new DataObject(id[2]);
...
DataObject dataObject[N] = new DataObject(id[N]);
// The 'DataObject' class has its own connection to the database,
// so each instance of the object should use its own connection.
// It also has a "run" method, which contains all the tasks required.
Executor ex = Executors.newFixedThreadPool(10);
for(i=0;i<=N;i++) {
ex.execute(dataObject[i]);
}
// Here where the problem is: Each instance creates a new connection,
// but every DML from any of the objects is cluttered in just one connection
// (in MySQL command line, "SHOW PROCESSLIST;" throws every connection, and all but
// one are idle).
你能为我指出正确的方向吗?
谢谢