將csv檔案匯入mysql
阿新 • • 發佈:2018-12-17
1.資料準備
將手頭的excel或者number資料另存為.csv檔案,方便後面的匯入
2.資料庫的準備
這裡登入資料庫,選擇對應的database,然後再建立相應的表,這裡要注意表的欄位型別和數目要和csv檔案對應
create table `r_vn_city_level`( city char(64) not null, level char(10) not null, primary key (`city`,`level`)) charset utf8;
3.匯入資料
這裡是最關鍵的一步,也最容易出錯,先看匯入的命令:
load data infile '/home/python/Desktop/test.csv' into table r_vn_city_level fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';
如果就這樣匯入會出錯,錯誤如下:
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
輸入命令:
show global variables like '%secure%';
這裡secure_file_priv這個欄位可能有三種值:
-
ure_file_priv的值為null ,表示限制mysqld 不允許匯入|匯出
-
當secure_file_priv的值為/tmp/ ,表示限制mysqld 的匯入|匯出只能發生在/tmp/目錄下
-
當secure_file_priv的值沒有具體值時,表示不對mysqld 的匯入|匯出做限制
所以我們需要對其進行設定,這裡我們vim開啟mysql的配置檔案,我這裡的命令如下:
進入配置檔案後,將secure_file_priv新增或者修改為:
secure_file_priv=''
然後儲存關閉,重啟mysql服務,終端輸入:
service mysql restart
這時重新輸入匯入檔案的命令,別急,還會報錯:
大致意思就是說找不到這個檔案,可是明明路徑是對的呀,怎麼解決呢?很簡單,只需要加上local這個命令:
load data local infile '/home/python/Desktop/test.csv' into table r_vn_city_level fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';
接下來再執行一遍,就可以匯入成功了!