Java CSV 文件解析并加载到 MySQL 数据库
以下是一个解析 CSV 文件并将其加载到 MySQL 数据库的 Java 程序示例:
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CSVLoader {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/your_database_name";
private static final String DB_USER = "your_username";
private static final String DB_PASSWORD = "your_password";
public static void main(String[] args) {
String csvFile = "path/to/your/csv/file.csv";
String tableName = "your_table_name";
try (Connection connection = getDBConnection();
BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
// Read the first line of the CSV file as column names
String line = br.readLine();
String[] columns = line.split(",");
// Create the SQL query to create the table
StringBuilder createTableQuery = new StringBuilder("CREATE TABLE IF NOT EXISTS ")
.append(tableName)
.append("(");
for (String column : columns) {
createTableQuery.append(column).append(" VARCHAR(255),");
}
createTableQuery.setLength(createTableQuery.length() - 1);
createTableQuery.append(")");
// Execute the create table query
executeQuery(createTableQuery.toString(), connection);
// Prepare the insert statement
StringBuilder insertQuery = new StringBuilder("INSERT INTO ")
.append(tableName)
.append("(")
.append(line)
.append(") VALUES (");
for (int i = 0; i < columns.length; i++) {
insertQuery.append("?, ");
}
insertQuery.setLength(insertQuery.length() - 1);
insertQuery.append(")");
// Read the remaining lines of the CSV file and insert into the table
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery.toString());
for (int i = 0; i < values.length; i++) {
preparedStatement.setString(i + 1, values[i]);
}
preparedStatement.executeUpdate();
}
System.out.println("CSV data loaded into the database successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getDBConnection() throws ClassNotFoundException, SQLException {
Class.forName(DB_DRIVER);
return DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
}
private static void executeQuery(String query, Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.executeUpdate();
}
}
在上面的示例中,你需要将以下变量替换为你的数据库连接信息:
DB_CONNECTION:数据库连接 URL,包括数据库名称。DB_USER:数据库用户名。DB_PASSWORD:数据库密码。
同时,将以下变量替换为你的 CSV 文件路径和表名:
csvFile:CSV 文件的路径。tableName:要插入数据的表名。
请确保在运行该程序之前,已经添加了适当的 MySQL JDBC 驱动程序依赖项。
原文地址: http://www.cveoy.top/t/topic/fEHT 著作权归作者所有。请勿转载和采集!