1.使用jar驱动自带的CopyManager(我这里使用的是postgresql-9.4.1212.jre7.jar)
public class PGPool {
PGPoolingDataSource source = new PGPoolingDataSource();
public PGPool(){
//PG database server name
source.setServerName("数据库ip");
//PG db port number
source.setPortNumber(端口);
//PG database name
source.setDatabaseName("数据库");
source.setUser("账号");
source.setPassword("密码");
source.setMaxConnections(3);
}
public Connection getConn(){
try{
return source.getConnection();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
@Test
public void testCopy() {
String fileUploadSavePath="C:\\Users\\Administrator.SKY-20170224BTQ\\Desktop\\";
String savedFileName="bendigongcan(1).csv";
String tableName = "smartinsight.test_tpm";
FileInputStream fileInputStream = null;
try {
try {
PGPool pool = new PGPool();
CopyManager copyManager = new CopyManager((BaseConnection)pool.getConn().getMetaData().getConnection());
// 程序csv文件路径
fileInputStream = new FileInputStream(fileUploadSavePath+savedFileName);
//如果导入字段与文件中完全相同可以不指定("copy tablename FROM STDIN delimiter ',' csv header encoding 'GBK'")
String sql = "COPY " + tableName + "(province,city,region,cgi,chinesename,covertype,scenario,iscore,iscounty,istown,isvillage,iscityproper,vendor,flag,earfcnflag,isimportantscenario,admin_area,large_scenario,small_scenario,grid,optiroom,islivearea,ishospital,gaosuname,gaotiename,elevate,iszbcj,isjtsn) FROM STDIN delimiter ',' csv header encoding 'GBK'";//指定分隔符和编码 默认是utf-8程序编码
log.debug(sql);
copyManager.copyIn(sql, fileInputStream);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.在数据库端命令执行本地文件
copy test_tpm from 'C:\\\\Users\\\\Administrator\\\\Desktop\\sshtest\\\\bendigongcan(1).csv'
delimiter ',' csv header encoding 'GBK';
来源:oschina
链接:https://my.oschina.net/u/257654/blog/1862679