PostgreSQL:Java使用CopyManager實現客戶端檔案COPY匯入 .
阿新 • • 發佈:2019-01-29
在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中,可以通過設定流的方式,設定需要匯入的客戶端本地檔案。
public void copyFromFile(Connection connection, String filePath, String tableName) throws SQLException, IOException { FileInputStream fileInputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileInputStream = new FileInputStream(filePath); copyManager.copyIn("COPY " + tableName + " FROM STDIN", fileInputStream); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
另外,還可以使用COPY table_name TO STDOUT來匯出資料檔案到本地,和上面的匯入相反,可以用於資料庫備份。此外,還支援匯出一個SQL查詢結果:
COPY (SELECT columns FROM table_name WHERE ……) TO STDOUT;
Java程式碼如下:
public void copyToFile(Connection connection, String filePath, String tableOrQuery) throws SQLException, IOException { FileOutputStream fileOutputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileOutputStream = new FileOutputStream(filePath); copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT", fileOutputStream); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
使用方式:
// 將本地d:/data.txt檔案中的資料匯入到person_info表中
copyFromFile(connection, "d:/data.txt", "person_info");
// 將person_info中的資料匯出到本地檔案d:/data.txt
copyToFile(connection, "d:/data.txt", "person_info");
// 將SELECT p_name,p_age FROM person_info查詢結果匯出到本地檔案d:/data.txt
copyToFile(connection, "d:/data.txt", "(SELECT p_name,p_age FROM person_info)");