1. 數據導入
使用load data infile語句加載數據
load data infile '/mysql_data/employee_name.csv' into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
文件名可以是一個完整的路徑,指定其確切的位置。如果是相對目錄,則會被解析於相對於客戶機程序啓動的目錄。這裏建議使用絕對路徑。
如果文件開頭有想要忽略的行,則可以使用ignore n lines指定忽略。如
load data infile '/mysql_data/employee_name.csv' into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n'
ignore 1 lines;
也可以用replace或ignore來處理重複的行,建議使用ignore。
load data infile '/mysql_data/employee_name.csv' replace into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
或
load data infile '/mysql_data/employee_name.csv' ignore into table employee_names
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';
2. 數據導出
導出爲文件
可以使用 select into outfile語句將輸出結果保存到文件中。在導出的時候可以指定行列分隔符,方便再導入到其他數據平臺。
select first_name,second_name into outfile 'employee_name.csv'
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n'
from employees
limit 10;
則數據將會被輸出到{secure_file_priv}/{database_name}指定的路徑中。如果文件已經存在,則數據導出會失敗,所以每次執行或將文件移動到其他位置時都需要提供一個唯一的名稱。
注:secure_file_priv的路徑可以在配置文件my.cnf中查看。
可以將secure_file_priv值設置爲「.」,這樣數據導出就不會到相對路徑下。導出的時候可以寫一個絕對路徑,則數據會被導出到該絕對路徑下。
另存爲表(可用於數據備份)
- 如果表不存在
create table first_name_only as
select distinct first_name
from employees;
- 如果表已經存在
insert into first_name_only
select distinct first_name
from employees;
當表中有PRIMARY KEY字段時,爲了避免重複,可以使用insert ignore。
其實在實際工作中,我們很少用命令行來加載數據到數據庫表中的。通常情況下是會使用一些可視化的客戶端(如navicate)進行數據的導入。