PostgreSQL:Java使用CopyManager实现客户端文件COPY导入

MySQL中,可以使用LOAD DATA INFILE和LOAD DATA LOCAL INFILE两种方式导入文本文件中的数据到数据库表中,速度非常快。其中LOAD DATA INFILE使用的文件要位于MySQL所在服务器上,LOAD DATA LOCAL INFILE则使用的是客户端的文件。

LOAD DATA INFILE 'data.txt' INTO TABLE table_name;
LOAD DATA LOCAL INFILE 'data.txt' INTO TABLE table_name;

在PostgreSQL中也可以导入相同类型的文本文件,使用的是COPY命令:

COPY table_name FROM 'data.txt';

但是这个语句只能导入PostgreSQL所在服务器上的文件,要想导入客户端文件,就需要使用下面的语句:

COPY table_name FROM STDIN;

Java中,可以通过设置流的方式,设置需要导入的客户端本地文件。

 

[java] view plain copy
 
  1. public void copyFromFile(Connection connection, String filePath, String tableName)   
  2.         throws SQLException, IOException {  
  3.       
  4.     FileInputStream fileInputStream = null;  
  5.   
  6.     try {  
  7.         CopyManager copyManager = new CopyManager((BaseConnection)connection);  
  8.         fileInputStream = new FileInputStream(filePath);  
  9.         copyManager.copyIn("COPY " + tableName + " FROM STDIN", fileInputStream);  
  10.     } finally {  
  11.         if (fileInputStream != null) {  
  12.             try {  
  13.                 fileInputStream.close();  
  14.             } catch (IOException e) {  
  15.                 e.printStackTrace();  
  16.             }  
  17.         }  
  18.     }  
  19. }  


另外,还可以使用COPY table_name TO STDOUT来导出数据文件到本地,和上面的导入相反,可以用于数据库备份。此外,还支持导出一个SQL查询结果:

 

COPY (SELECT columns FROM table_name WHERE ……) TO STDOUT;

Java代码如下:

 

[java] view plain copy
 
  1. public void copyToFile(Connection connection, String filePath, String tableOrQuery)   
  2.         throws SQLException, IOException {  
  3.       
  4.     FileOutputStream fileOutputStream = null;  
  5.   
  6.     try {  
  7.         CopyManager copyManager = new CopyManager((BaseConnection)connection);  
  8.         fileOutputStream = new FileOutputStream(filePath);  
  9.         copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT", fileOutputStream);  
  10.     } finally {  
  11.         if (fileOutputStream != null) {  
  12.             try {  
  13.                 fileOutputStream.close();  
  14.             } catch (IOException e) {  
  15.                 e.printStackTrace();  
  16.             }  
  17.         }  
  18.     }  
  19. }  

 

 

使用方式:

 

[java] view plain copy
 
  1. // 将本地d:/data.txt文件中的数据导入到person_info表中  
  2. copyFromFile(connection, "d:/data.txt", "person_info");  
  3. // 将person_info中的数据导出到本地文件d:/data.txt  
  4. copyToFile(connection, "d:/data.txt", "person_info");  
  5. // 将SELECT p_name,p_age FROM person_info查询结果导出到本地文件d:/data.txt  
  6. copyToFile(connection, "d:/data.txt", "(SELECT p_name,p_age FROM person_info)");  

 

 

 

 

转载自:http://blog.csdn.net/xiao__gui/article/details/12090341

posted on 2017-04-06 17:13  手撕高达的村长  阅读(4896)  评论(0编辑  收藏  举报

导航