相关文章推荐


在windows版的pgAdmin中,可以轻松的导入数据,但是如果要在pgAdmin的界面中用命令来导入的话就不好办了(使用cmd copy命令除外)

这里介绍一下如何使用JDBC的方式来导入一个csv文件到数据库表

init.sql

CREATE TABLE public.test (
id character varying NOT NULL,
name character varying
);
INSERT INTO public.test VALUES ('1', 'Daniel');
INSERT INTO public.test VALUES ('2', 'Lily');

input.csv

id,name
3,Jack
4,Rose

Maven依赖

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>

LoadCSVFile.java

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);
}
}

PostgreSQL使用jdbc导入csv文件_postgresql



 
推荐文章