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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM