java postgresql csv文件数据导入

1.使用jar驱动自带的CopyManager(我这里使用的是postgresql-9.4.1212.jre7.jar)sql

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

//若是导入字段与文件中彻底相同能够不指定("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();  
                }  
            }  
        }  
    }post

2.在数据库端命令执行本地文件编码

copy test_tpm from 'C:\\\\Users\\\\Administrator\\\\Desktop\\sshtest\\\\bendigongcan(1).csv' 
delimiter ',' csv header encoding 'GBK'; spa

相关文章
相关标签/搜索