如何在几毫秒内将数千条记录更新到MySQL DB中?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (141)

我想在不到一秒的时间内将大约10K记录更新到MySQL DB中,我写了下面的代码,但大约需要6-8秒才能将记录列表更新到DB中。

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();
                }
            }   
       }

有什么方法能够提高速率吗?

提问于
用户回答回答于

你可以将INSERT批处理到临时表中rewriteBatchedStatements=true,然后使用单个UPDATE语句来更新主表格,而不是对单个UPDATE进行批量处理,以下代码执行大约需要2.5秒:

long t0 = System.nanoTime();
conn.setAutoCommit(false);

String sql = null;
sql = "UPDATE personal_info SET result=?, score=?, uploadState=? WHERE CandidateID=?";
PreparedStatement ps = conn.prepareStatement(sql);
String tag = "X";
for (int i = 1; i <= 10000; i++) {
    ps.setString(1, String.format("result_%s_%d", tag, i));
    ps.setInt(2, 200000 + i);
    ps.setString(3, String.format("state_%s_%d", tag, i));
    ps.setInt(4, i);
    ps.addBatch();
}
ps.executeBatch();
conn.commit();
System.out.printf("%d ms%n", (System.nanoTime() - t0) / 1000000);

这个版本的代码大约需要1.3秒:

long t0 = System.nanoTime();
conn.setAutoCommit(false);

String sql = null;
Statement st = conn.createStatement();
st.execute("CREATE TEMPORARY TABLE tmp (CandidateID INT, result VARCHAR(255), score INT, uploadState VARCHAR(255))");
sql = "INSERT INTO tmp (result, score, uploadState, CandidateID) VALUES (?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
String tag = "Y";
for (int i = 1; i <= 10000; i++) {
    ps.setString(1, String.format("result_%s_%d", tag, i));
    ps.setInt(2, 400000 + i);
    ps.setString(3, String.format("state_%s_%d", tag, i));
    ps.setInt(4, i);
    ps.addBatch();
}
ps.executeBatch();
sql = 
          "UPDATE personal_info pi INNER JOIN tmp ON tmp.CandidateID=pi.CandidateID "
        + "SET pi.result=tmp.result, pi.score=tmp.score, pi.uploadState=tmp.uploadState";
st.execute(sql);
conn.commit();
System.out.printf("%d ms%n", (System.nanoTime() - t0) / 1000000);
用户回答回答于

首先在for循环之前初始化prepareStatement,其次,应该避免pstm.executeBatch(),

每次循环执行会花费更多的资源。

Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
myConn.setAutoCommit(false);
String sql = "UPDATE personal_info SET result = ?, score = ?, uploadState = ? "
                + " WHERE CandidateID = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
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];
    pstm.setString(1, result);
    pstm.setInt(2, score);
    pstm.setString(3, uploadState);
    pstm.setInt(4, candidateID);
    pstm.addBatch();
    if(i%500==0){//execute when it meet a specified amount
        pstm.executeBatch();
    }
}
pstm.executeBatch();
myConn.commit();
myConn.setAutoCommit(true);

扫码关注云+社区

领取腾讯云代金券