1. 程式人生 > >用LOAD命令批量匯入檔案內容到MySQL資料庫中

用LOAD命令批量匯入檔案內容到MySQL資料庫中

該命令:

Load Data Local InFile 'dir.txt' Into Table table_name;

(規範貌似是除了檔名和表名是小寫,其他全部是大寫,我自己打的時候懶得分大小寫,它也預設能識別,不過好像不太好)

忽略大小寫,默認同行資料間為'\t',一行以'\n'結束,把檔案裡的資料安行`讀入到資料庫中

過程中遇到過的問題:

1.預設安裝時沒有配置,會顯示:
The used command is not allowed with this MySQL version

解決辦法:
修改配置檔案:

sudo nano(或vim) /etc/mysql/my.cnf

找到[mysqld]和[mysql],在下面加上"local-infile=1"

--------my.cnf中:

[mysqld]
local-infile=1

[mysql]
local-infile=1

Save and quit the file.(nano 為 ctrl+x)
-----------------------

sudo /etc/init.d/mysql restart

再進入資料庫就可以用了

參考:

http://greproot.com/the-used-command-is-not-allowed-with-this-mysql-version/
其他關於load的用法:http://www.cnblogs.com/ggjucheng/archive/2012/11/05/2755683.html

2.經過以上修改可能只能成功一次,之後再使用時又會有問題:

ERROR 29 (HY000): File '  ' not found (Errcode: 13)

原因:mysql強制編碼,檔案沒有寫入許可權
解決方法:
sudo nano(vim) /etc/apparmor.d/usr.sbin.mysqld
把要匯入的檔案的路徑加到最後,

eg./home/資料夾/* r,           
      /home/資料夾/* rw,(兩個都要)

儲存退出

sudo /etc/init.d/apparmor reload

參考:http://blog.csdn.net/ljasdf123/article/details/17465767

和 Load Data InFile 相反的命令是
Select * From table_name Into OutFile 'C:/Data_OutFile.txt';

把資料表的資料匯出到txt

遇到的問題:

Can't create/write to file..... (Errcode:13)

原因:許可權不夠

方法:修改配置檔案
sudo nano(vim) /etc/mysql/my.cnf
找到tmpdir 這一欄, 修改為/var/lib/mysql/tmp(這是要匯出檔案的地方,貌似必須與datadir相對應,我移植了資料庫,所以路徑會跟預設不一樣,關於移植資料庫看上一篇筆記.匯出的地方沒有檢視許可權,在命令列下:sudo su 切換成root使用者,再進入相應位置檢視

以上都是通過改資料庫配置解決的問題,還有其他一些問題也可以通過改資料庫配置解決.

以上都是在ubuntu命令列下才能成功,在python下用cursor操作資料庫和用Django操作暫時沒法使用LOAD,也暫時沒發現對應的語句,有待繼續學習.