在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)");