小弟在使用MYSQL数据库的时候,遇到一个奇怪的问题:为什么我使用批量插入和逐条插入的性能是差不多的?package com.ray.test.db;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class App { public static void main(String[] argv) {
if (!testClass())
return; try {
String url = "jdbc:mysql://localhost:3306/test?user=root&password=220315";
Connection conn = DriverManager.getConnection(url);
if (!conn.isClosed())
System.out.println("資料庫連線成功"); // java.sql.PreparedStatement caller =
// conn.prepareStatement("insert into test values (?)");
// System.out.println("start excute : " +
// System.currentTimeMillis());
// for (int i = 0; i < 10000; i++) {
// caller.setInt(1, i);
// caller.executeUpdate();
// }
// System.out.println("finish excute : " +
// System.currentTimeMillis()); java.sql.PreparedStatement caller = conn.prepareStatement("insert into test values (?)");
System.out.println("start excute : " + System.currentTimeMillis());
for (int i = 0; i < 10000; i++) {
caller.setInt(1, i);
caller.addBatch();
}
caller.executeBatch();
System.out.println("finish excute : " + System.currentTimeMillis());
conn.close();
} catch (SQLException e) {
System.out.println("Exception occur, e.getMessage()=" + e.getMessage());
} } private static boolean testClass() {
try {
Class.forName("com.mysql.jdbc.Driver");
return true;
} catch (ClassNotFoundException e) {
System.out.println("找不到驅動程式類別, e.getMessage()=" + e.getMessage());
}
return false;
}}    被注释掉的代码是逐行插入的,用时1090毫秒,而未注释的代码是使用了批量插入的,用时1073毫秒秒。怎么只差了17毫秒而已,没有体现出批量插入的优势啊!?

解决方案 »

  1.   

    mysql默认是把批量插入给关闭的,你需要在jdbcurl上加上参数rewriteBatchedStatements=true,不懂的话你可以搜下rewriteBatchedStatements   ,还有就是注意事务的处理
      

  2.   

        已经在连接语句里添加了rewriteBatchedStatements=true,但是速度没有提升。
         注意事务的处理能说具体点吗?
         
      

  3.   

    你将数据保存在TXT文件中,再用LOAD DATA导入试试
      

  4.   

    insert into table values (),(),(),(),(),(), .........这样才算批量插入
      

  5.   

        刚刚试了如下代码:
        System.out.println("start excute: \t" + System.currentTimeMillis());
    StringBuilder builder = new StringBuilder("INSERT INTO test VALUES ");
    for (int i = 0; i < 10000; i++) {
    if (i == 9999)
    builder.append("(9999)");
    else
    builder.append("( " + i + " ), ");
    }
    Statement sm = conn.createStatement();
    sm.execute(builder.toString());
    System.out.println("finish excute: \t" + System.currentTimeMillis());
         用时36毫秒,目前最快的方式了。
      

  6.   

        不是说,MYSQL3.1.3以上,JAVA 驱动 5.1.8以上已经支持MYSQL的批量插入了么?为什么没效果呢?难不成,真的生成insert into table values (),(),(),(),(),(), .........这样的SQL语句来实现批量插入?
      

  7.   

    最后还是使用StringBuilder来手动生成7楼所说形式的SQL语言来实现数据插入的。
    性能还不错,能够达到1W行每秒的插入速度。结贴~