java读取多个csv文件导入到达梦数据库
时间: 2023-11-20 10:55:12 浏览: 86
java读取cvs文件并导入数据库
5星 · 资源好评率100%
以下是Java读取多个CSV文件并将其导入到达梦数据库的示例代码:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CsvToDatabase {
public static void main(String[] args) {
String jdbcUrl = "jdbc:dm://localhost:5236";
String username = "username";
String password = "password";
String driverName = "dm.jdbc.driver.DmDriver";
String csvFolderPath = "path/to/csv/folder";
String tableName = "table_name";
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(jdbcUrl, username, password);
File folder = new File(csvFolderPath);
File[] csvFiles = folder.listFiles((dir, name) -> name.endsWith(".csv"));
for (File csvFile : csvFiles) {
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line;
String[] headers = null;
String[] values;
int count = 0;
while ((line = br.readLine()) != null) {
if (count == 0) {
headers = line.split(",");
} else {
values = line.split(",");
String sql = "INSERT INTO " + tableName + " (";
for (int i = 0; i < headers.length; i++) {
sql += headers[i];
if (i != headers.length - 1) {
sql += ",";
}
}
sql += ") VALUES (";
for (int i = 0; i < values.length; i++) {
sql += "?";
if (i != values.length - 1) {
sql += ",";
}
}
sql += ")";
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < values.length; i++) {
pstmt.setString(i + 1, values[i]);
}
pstmt.executeUpdate();
}
count++;
}
br.close();
}
System.out.println("CSV files imported successfully.");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
请注意,您需要将代码中的以下变量替换为您自己的值:
- jdbcUrl:到达梦数据库的JDBC URL。
- username:数据库用户名。
- password:数据库密码。
- driverName:JDBC驱动程序的完整类名。
- csvFolderPath:包含CSV文件的文件夹的路径。
- tableName:要将数据插入的表的名称。
阅读全文