package dao;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
/**
* @Author Daniel
* @Description 导入csv文件到数据库表
**/
public class LoadCSVFile {
private Connection connection = null;
public Connection getConnection() {
try {
// 注册postgresql驱动
Class.forName("org.postgresql.Driver").newInstance();
//url、用户名、密码
String url = "jdbc:postgresql://localhost:5432/test";
String username = "postgres";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
// 执行多条SQL语句
public void executeSQL(Connection conn, String[] sqlArray) {
// 直接返回Statement对象
Statement statement;
try {
statement = conn.createStatement();
for (String sql : sqlArray) {
statement.addBatch(sql);
}
statement.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException, IOException {
LoadCSVFile load = new LoadCSVFile();
Connection conn = load.getConnection();
// 查看表中目前的数据,并清空表
String[] initArray = {"truncate table test"};
load.executeSQL(conn, initArray);
// 这里的核心就是使用org.postgresql.copy.CopyManager类来完成copy操作
CopyManager copyManager = new CopyManager((BaseConnection) conn);
FileReader fileReader = new FileReader("C:/input.csv");
// 导入带有表头的数据
long rows = copyManager.copyIn("COPY TEST FROM STDIN WITH CSV HEADER", fileReader);
System.out.println("INSERT " + rows + "\n\nQuery returned successfully.");
load.close(conn);
}
}