Java 使用 Stream API 解析 CSV 文件并批量导入 Doris 数据库
以下是一个使用 Java 解析 CSV 文件并将数据写入 Doris 数据库的示例程序:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CsvDataLoader {
public static void main(String[] args) {
String csvFilePath = '/path/to/csv/file.csv';
String jdbcUrl = 'jdbc:mysql://localhost:3306/doris_db';
String username = 'username';
String password = 'password';
String tableName = 'data_table';
try (BufferedReader reader = new BufferedReader(new FileReader(csvFilePath));
Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
List<String> fieldNames = Arrays.asList(reader.readLine().split(','));
String fieldPlaceholders = fieldNames.stream()
.map(fieldName -> '?')
.collect(Collectors.joining(', '));
String insertQuery = String.format('INSERT INTO %s (%s) VALUES (%s)',
tableName, String.join(', ', fieldNames), fieldPlaceholders);
String line;
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
while ((line = reader.readLine()) != null) {
String[] fields = line.split(',');
for (int i = 0; i < fields.length; i++) {
preparedStatement.setObject(i + 1, fields[i]);
}
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
System.out.println('Data loaded successfully!');
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
请注意以下几点:
- 需要将
csvFilePath替换为实际的 CSV 文件路径。 - 需要将
jdbcUrl、username和password替换为实际的 Doris 数据库连接信息。 - 需要将
tableName替换为实际的目标表名。 - 该示例假设 CSV 文件中的数据类型均为字符串,如果需要根据表结构将字段类型进行转换,请修改代码适配。
- 该示例使用了 Java 8 的 Stream API 来处理数据,需要确保你的项目使用的是 Java 8 或更高版本。
运行该程序后,它将读取 CSV 文件的第一行作为字段名,然后将数据批量插入到 Doris 数据库的目标表中。
原文地址: https://www.cveoy.top/t/topic/fJVh 著作权归作者所有。请勿转载和采集!