public class Test {
private static final String DRIVER_CLASS_NAME = "";
private static final String JDBC_URL = "";
private static final String USER = "";
private static final String PASSWORD = "";
public static void main(String[] args) {
int count = 10; // 插入记录的数目
Object[][] params = new Object[count][];
for (int i = 0; i < count; i++){
// 将每条记录的数据插入数组
params[i] = new Object[] { "", "", "" };
}
batch(params);
}
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
return conn;
} catch (Exception e) {
return null;
}
}
public static void batch(Object[][] params) {
QueryRunner queryRunner = new QueryRunner(true);
String sql = "INSERT INTO TABLE_NAME VALUES (?,?,?)";
try {
queryRunner.batch(getConnection(), sql, params);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
方法2 批量操作+事务提交
private String url = "jdbc:mysql://localhost:3306/test01?rewriteBatchedStatements=true";
private String user = "root";
private String password = "123456";
@Test
public void Test(){
Connection conn = null;
PreparedStatement pstm =null;
ResultSet rt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO userinfo(uid,uname,uphone,uaddress) VALUES(?,CONCAT('姓名',?),?,?)";
pstm = conn.prepareStatement(sql);
conn.setAutoCommit(false);
Long startTime = System.currentTimeMillis();
Random rand = new Random();
int a,b,c,d;
for (int i = 1; i <= 100000; i++) {
pstm.setInt(1, i);
pstm.setInt(2, i);
a = rand.nextInt(10);
b = rand.nextInt(10);
c = rand.nextInt(10);
d = rand.nextInt(10);
pstm.setString(3, "188"+a+"88"+b+c+"66"+d);
pstm.setString(4, "xxxxxxxxxx_"+"188"+a+"88"+b+c+"66"+d);
pstm.addBatch();
}
pstm.executeBatch();
conn.commit();
Long endTime = System.currentTimeMillis();
System.out.println("OK,用时:" + (endTime - startTime));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally{
if(pstm!=null){
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}