SELECT ... INTO OUTFILE
导出数据
https://dev.mysql.com/doc/refman/8.0/en/select-into.html
SELECT...INTO OUTFILE
是 MySQL 中用于将查询结果导出到文件的语法。允许你将查询的结果写入一个文本文件。
语法 1 2 3 4 5 SELECT * FROM Table INTO OUTFILE '/tmp/employee_data_1.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\' LINES TERMINATED BY '\n' ;
示例 1 2 3 4 5 SELECT id , name , email INTO OUTFILE '/tmp/user_data.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' FROM users ;
SELECT ... INTO OUTFILE
注意事项
SELECT...INTO OUTFILE 'file_name'
形式的 SELECT 可以把被选择的行写入一个文件中。该文件被创建到服务器主机上,因此您必须拥有FILE权限,才能使用此语法。
输出不能是一个已存在的文件。防止文件数据被篡改。
你需要有一个登陆服务器的账号来检索文件。否则 SELECT ... INTO OUTFILE
不会起任何作用。
在UNIX中,该文件被创建后是可读的,权限由MySQL服务器所拥有。这意味着,虽然你就可以读取该文件,但可能无法将其删除。
LOAD DATA INFILE
导入数据
https://dev.mysql.com/doc/refman/8.0/en/load-data.html
对 SELECT ... INTO OUTFILE
导出的文本文件,可以通过 LOAD DATA INFILE
命令导入到表里。LOAD DATA INFILE
是 SELECT ... INTO OUTFILE
的逆操作。
语法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 LOAD DATA [LOW_PRIORITY | CONCURRENT ] [LOCAL ] INFILE 'file_name' [REPLACE | IGNORE ] INTO TABLE tbl_name [PARTITION (partition_name [, partition_name] ...)] [CHARACTER SET charset_name] [{FIELDS | COLUMNS } [TERMINATED BY 'string' ] [[OPTIONALLY ] ENCLOSED BY 'char' ] [ESCAPED BY 'char' ] ] [LINES [STARTING BY 'string' ] [TERMINATED BY 'string' ] ] [IGNORE number {LINES | ROWS }] [(col_name_or_user_var [, col_name_or_user_var] ...)] [SET col_name={expr | DEFAULT } [, col_name={expr | DEFAULT }] ...]
示例 1 2 load data infile '/usr/local/mysql/backup/students.txt' ignore into table students fields terminated by ',' enclosed by '"' lines terminated by '\r\n' ;