MySQL的batch模式
MySQL的batch模式,其实也就是批处理模式。它比一条条插入的效率高多了。
这是从网上copy下来的例子:
首先使用普通的方式插入100万条数据,使用时间81948毫秒
程序如下:
public class Test {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
long start = System.currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/xx",
"xx", "xx");
connection.setAutoCommit(false);
PreparedStatement cmd = connection
.prepareStatement("insert into test values(?,?)");
for (int i = 0; i < 1000000; i++) {
cmd.setInt(1, i);
cmd.setString(2, "test");
cmd.executeUpdate();
}
connection.commit();
cmd.close();
connection.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
使用批量处理,仅用7189毫秒,提升效果非常明显。
程序如下:
public class Test {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
long start = System.currentTimeMillis();
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection(
"jdbc:mysql://127.0.0.1:3306/xx?rewriteBatchedStatements=true",
"xx", "xx");
connection.setAutoCommit(false);
PreparedStatement cmd = connection
.prepareStatement("insert into test values(?,?)");
for (int i = 0; i < 1000000; i++) {
cmd.setInt(1, i);
cmd.setString(2, "test");
cmd.addBatch();
if(i%1000==0){
cmd.executeBatch();
}
}
cmd.executeBatch();
connection.commit();
cmd.close();
connection.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
为啥效果差异会这么大呢?
首先得明确一个概念:
字符串解析是非常非常耗时的!!!正则表达式写几个了解一下(虽然数据库用的不仅仅是正则)。
所以SQL引擎的问题就来了,这里解析SQL语句如何更高效?答案是它使用了缓存,每个SQL生成查询计划后都会被缓存起来,下次来一个相同的SQL,不用解析,直接拿出查询计划。