【发布时间】:2018-11-21 16:45:25
【问题描述】:
我想在一秒钟内将大约 10K 条记录更新到 MySQL 数据库中。我编写了下面的代码,大约需要 6-8 秒才能将记录列表更新到数据库中。
public void updateResultList(List<?> list) {
String user = "root";
String pass = "root";
String jdbcUrl = "jdbc:mysql://12.1.1.1/db_1?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
PreparedStatement pstm = null;
try {
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
myConn.setAutoCommit(false);
for(int i=0; i<list.size(); i++) {
Object[] row = (Object[]) list.get(i);
int candidateID = Integer.valueOf(String.valueOf(row[0]));
String result = String.valueOf(row[14]);
int score = Integer.valueOf(String.valueOf(row[19]));
String uploadState = (String) row[20];
String sql = "UPDATE personal_info SET result = ?, score = ?, uploadState = ? "
+ " WHERE CandidateID = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
pstm.setString(1, result);
pstm.setInt(2, score);
pstm.setString(3, uploadState);
pstm.setInt(4, candidateID);
pstm.addBatch();
pstm.executeBatch();
}
myConn.commit();
myConn.setAutoCommit(true);
pstm.close();
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
try {
throw new ServletException(exc);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
请让我知道您的意见,以优化此代码以提高性能。
【问题讨论】:
-
尝试在
for循环之后调用executeBatch()。 -
我曾尝试在 for 循环外调用它,但它只更新最后一条记录。
-
提交后为什么要设置 autoCommit 为 true?
-
因为我一开始设置为false,所以最后默认设置为true。
-
您还需要将
pstm = (PreparedStatement) myConn.prepareStatement(sql);移出循环...