我采用的是mysql数据库,插入100000条纪录,分为三部分测试,一是直接插入,二是使用executeBatch,三是批量是用executeBatch,下面试我得源码和测试结果。
Connection conn = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "qwe123");
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement("insert into tb_test values (?,?)");
String date = new java.util.Date().toString();
long l = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.executeUpdate();
conn.commit();
}
ps.executeBatch();
System.out.println(System.currentTimeMillis()-l);
long l1 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.addBatch();
conn.commit();
}
ps.executeBatch();
System.out.println(System.currentTimeMillis()-l1);
int a[] = new int[100];
Date b[] = new Date[100];
int j=0;
long l2 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.addBatch();
if (++j == 100) {
j = 0;
ps.executeBatch();
conn.commit();
}
} //end for
System.out.println(System.currentTimeMillis()-l2);
}
catch (Exception ex) {
ex.printStackTrace(System.out);
}
finally {
try {
conn.close();
}
catch (Exception ex) {}
}
测试结果为:
41590
43363
25877
将源码中的粗题不分去掉。就自动提交
28891
31956
25517
好像根本没有启到作用,在有篇文章上说“实MYSQL的驱程只是把原来的外部的循环移到了executeBatch()内部而已,还是每次更新都和数据庫进行一次交互”。如果真的这样,那就不奇怪了。别的数据库我没有是过,不知道是不是存在同样的问题!
Connection conn = null;
try {
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "qwe123");
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement("insert into tb_test values (?,?)");
String date = new java.util.Date().toString();
long l = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.executeUpdate();
conn.commit();
}
ps.executeBatch();
System.out.println(System.currentTimeMillis()-l);
long l1 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.addBatch();
conn.commit();
}
ps.executeBatch();
System.out.println(System.currentTimeMillis()-l1);
int a[] = new int[100];
Date b[] = new Date[100];
int j=0;
long l2 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
ps.setString(1, "axman");
ps.setString(2, date);
ps.addBatch();
if (++j == 100) {
j = 0;
ps.executeBatch();
conn.commit();
}
} //end for
System.out.println(System.currentTimeMillis()-l2);
}
catch (Exception ex) {
ex.printStackTrace(System.out);
}
finally {
try {
conn.close();
}
catch (Exception ex) {}
}
测试结果为:
41590
43363
25877
将源码中的粗题不分去掉。就自动提交
28891
31956
25517
好像根本没有启到作用,在有篇文章上说“实MYSQL的驱程只是把原来的外部的循环移到了executeBatch()内部而已,还是每次更新都和数据庫进行一次交互”。如果真的这样,那就不奇怪了。别的数据库我没有是过,不知道是不是存在同样的问题!