批量插入大量数据
public class InsertManyRecord {
@Test
public void insertMany() throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
String sql = "insert into test.t_user (account, password,nickname) values (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
statement.setObject(1, "dd" + i);
statement.setObject(2, "pwd" + i);
statement.setObject(3, "name" + i);
statement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000);
statement.close();
connection.close();
}
@Test
public void insertMany2() throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?rewriteBatchedStatements=true", "root", "123456");
String sql = "insert into test.t_user (account, password,nickname) values (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
statement.setObject(1, "dd" + i);
statement.setObject(2, "pwd" + i);
statement.setObject(3, "name" + i);
statement.addBatch();
}
statement.executeBatch();
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000);
statement.close();
connection.close();
}
}