请教java批量更新mysql,为什么update进程会sleep呢???那个数据库只有我一个人在用的,只执行一个select,然后依次根据id进行update,有时候update进程就sleep了.importjava.sql.Co...
请教java批量更新mysql,为什么update进程会sleep呢???那个数据库只有我一个人在用的,只执行一个select,然后依次根据id进行update,有时候update进程就sleep了.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
public class DBwriteThread implements Runnable {
private volatile ArrayBlockingQueue queue2;
private volatile ArrayBlockingQueue flag;
public DBwriteThread(ArrayBlockingQueue queue2,
ArrayBlockingQueue flag) {
this.queue2 = queue2;
this.flag = flag;
}
public void run() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/dev";
String user = "user";
String password = "password";
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
while ((flag.size() < 2) || (!(queue2.isEmpty()))) {
try {
String sql = "update SINA_LEARN_SAMPLE set PARSE_LINE=?,WORD=?,TIMES=?,FEATURE=? where document_id=";
Documents newDocument = queue2.take();
String sql1 = sql + (newDocument.getDocumentID());
String word;
String times;
String feature;
stmt = conn.prepareStatement(sql1);
word = ArrayListToString(newDocument.getWord());
times = ArrayListToString(newDocument.getTime());
feature = ArrayListToString(newDocument.getFeature());
stmt.setString(1, newDocument.getParseLine().get(0));
stmt.setString(2, word);
stmt.setString(3, times);
stmt.setString(4, feature);
stmt.executeUpdate();
conn.commit();
} catch (InterruptedException e1) {
break;
}
}
flag.put(5);
} catch (ClassNotFoundException e1) {
System.err.println("装载JDBC失败");
e1.printStackTrace();
} catch (SQLException e2) {
System.err.println("SQL异常");
e2.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public String ArrayListToString(ArrayList newArray) {
String result = null;
for (int i = 0; i < newArray.size(); i++) {
if (result == null) {
result = newArray.get(i);
} else {
result = result + "," + newArray.get(i);
}
}
return result;
}
}
展开