大批量数据插入数据库时怎么才能提高速度或性能
下面的测试程序
import java.sql.*;
//Table t1(c1 varchar(255),c2 varchar(255),c3 varchar(255),c4 varchar(255));
public class TestDB
{
public static void main(String[] args)
{
try
{
Class.forName("org.gjt.mm.mysql.Driver");
//Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException ex)
{
ex.printStackTrace();
}
String url = "jdbc:mysql://127.0.0.1:3306/test";
try
{
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
String v = "hellohellohellohellohellohellohellohellohellohellohellohello";
String sql = "insert into t1 values('" + v + "','" + v + "','" + v +
"','" + v + "')";
String sql1 = "insert into t1 values(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql1);
int count = 100000;
stmt.execute("delete from t1");
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++)
{
stmt.execute(sql);
}
System.out.println("用stmt execute 原始方式逐条添加记录耗时 : " + (System.currentTimeMillis() - start));
stmt.execute("delete from t1");
start = System.currentTimeMillis();
for (int i = 0; i < count; i++)
{
stmt.addBatch(sql);
}
stmt.executeBatch();
System.out.println("用stmt addBatch executeBatch 方式批量添加记录耗时 : " + (System.currentTimeMillis() - start));
stmt.execute("delete from t1");
start = System.currentTimeMillis();
for (int i = 0; i < count; i++)
{
pstmt.setString(1, v);
pstmt.setString(2, v);
pstmt.setString(3, v);
pstmt.setString(4, v);
pstmt.addBatch();
}
pstmt.executeBatch();
System.out.println("用pstmt addBatch executeBatch 方式批量添加记录耗时 : " + (System.currentTimeMillis() - start));
}
catch (SQLException ex1)
{
ex1.printStackTrace();
}
}
}
运行结果是:
用第一个驱动
用stmt execute 原始方式逐条添加记录耗时 : 20743
用stmt addBatch executeBatch 方式批量添加记录耗时 : 20046
用pstmt addBatch executeBatch 方式批量添加记录耗时 : 22091
用第二个驱动
用stmt execute 原始方式逐条添加记录耗时 : 20807
用stmt addBatch executeBatch 方式批量添加记录耗时 : 20854
用pstmt addBatch executeBatch 方式批量添加记录耗时 : 22356
用Batch方式,性能基本没什么影响,反而一条一条的插入到数据库快一点
有没有能显示著提高处理速度的方法呢?