JDBC批量插入数据

@Test
public void batchInsertMysqlData() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");

    connection.setAutoCommit(false);

    String sql = "INSERT INTO `product_air` VALUES (?, '1', '1', '1000', ?, null, null, null, ?, null, null, null, null, ?, null, null, null, null, null, null, ?, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)";

    String sql2 = "INSERT INTO `payment_detail` VALUES (?, ?, null, '支付宝', '携程', null, '1362', '购票支付')";

    String sql3 = "INSERT INTO `state_record` VALUES (?,?, '1')";

    PreparedStatement cmd = connection.prepareStatement(sql);

    PreparedStatement cmd2 = connection.prepareStatement(sql2);

    PreparedStatement cmd3 = connection.prepareStatement(sql3);

    for (int i = 0; i < 10000; i++) {
​​​​​​​
        cmd.setString(1, xxx);
        cmd.setString(2, xxx);
        cmd.setString(3, xxx);
        cmd.setString(4, xxx);
        cmd.setString(5, xxx);

        cmd2.setString(1, xxx);
        cmd2.setString(2, xxx);

        cmd3.setString(1, xxx);
        cmd3.setString(2, xxx);

        cmd.addBatch();
        cmd2.addBatch();
        cmd3.addBatch();

        //每1000次提交一次
        if (i != 0 && i % 1000 == 0) {
            cmd.executeBatch();
            cmd2.executeBatch();
            cmd3.executeBatch();
            connection.commit();
            cmd.clearBatch();
            cmd2.clearBatch();
            cmd3.clearBatch();
        }
    }
    cmd.executeBatch();
    cmd2.executeBatch();
    cmd3.executeBatch();
    connection.commit();
    cmd.close();
    cmd2.close();
    cmd3.close();
    connection.close();
}

 

你可能感兴趣的:(JAVA)