mysql的into outfile/load data infile可以用于数据的导入导出。
跟mysqldump不同的是,into outfile直接将数据输出到问题,数据本身是没有加密的,文件本身没有ddl建表语句,也没有insert语句。相当于将表数据导成csv表格文件
select .. into outfile语法:
SELECT ... into_option: { INTO OUTFILE 'file_name' [CHARACTER SET charset_name] export_options | INTO DUMPFILE 'file_name' | INTO var_name [, var_name] ... }load data infile ..into table语法
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}] ...]
虽然语法选项很多,其中fields terminated by ',' enclosed by '`' lines terminated by '\r\n'是比较关键的
fields terminated by ',' 以 , 分割字段
enclosed by '`' 以 ` 围起字段,如果没有enclose可能导入时会遇到识别字段的问题,比如数据本身有,号,识别就错位了
lines terminated by '\r\n' \r\n为换行符, \r\n是linux的换行符,如果没有换行符导入数据可能只有1行
当然符号是自定义的,尽量使用数据中不太可能出现的字符
导出测试:
mysql> select * from lzldb.test1 into outfile '/tmp/lzldb_test1.txt' fields terminated by ',' enclosed by '`' lines terminated by '\r\n' ; Query OK, 7 rows affected (0.01 sec) mysql> create table lzldb.test2 like lzldb.test1; Query OK, 0 rows affected (0.02 sec) mysql> load data infile '/tmp/lzldb_test1.txt' into table lzldb.test2 fields terminated by ',' enclosed by '`' lines terminated by '\r\n' ; Query OK, 7 rows affected (0.00 sec) Records: 7 Deleted: 0 Skipped: 0 Warnings: 0