Linux环境MySQL将select结果导入csv文件

直接使用mysql导出csv方法
我们可以使用into outfile的方式。

1.语句的格式与作用
into outfile ‘导出的目录和文件名’
指定导出的目录和文件名

fields terminated by ‘字段间分隔符’
定义字段间的分隔符

optionally enclosed by ‘字段包围符’
定义包围字段的字符(数值型字段无效)

lines terminated by ‘行间分隔符’

定义每行的分隔符

2.直接将查询出来的结果保存为csv文件
执行sql将查询结果保存为文件pir_50w_10.csv,退出到MySQL容器内,查看安全目录/tmp下的文件,可以看到目录下已有生成的新文件pir_50w_10.csv,通过head命令查看保存好的文件内容。

mysql> select id from pir_50w limit 10 into outfile '/tmp/pir_50w_10.csv';
Query OK, 10 rows affected (0.00 sec)

mysql>
mysql>
mysql> exit
Bye
sh-4.4#
sh-4.4# ls
bin   docker-entrypoint-initdb.d  home   media  proc  sbin  tmp
boot  entrypoint.sh               lib    mnt    root  srv   usr
dev   etc                         lib64  opt    run   sys   var
sh-4.4#
sh-4.4# cd tmp/
sh-4.4#
sh-4.4# ls
pir_1000w.sql  pir_100w.sql  pir_50w.sql  pir_50w_10.csv  pir_75w.sql
sh-4.4#
sh-4.4# head pir_50w_10.csv
00003e3b9e5336685200ae85d21b4f5e
000053b1e684c9e7ea73727b2238ce18
00005d011db80a956aab176cc94d1d37
0000a0f5746d603088ac968c91b085b5
0000b2815cc3c2b56867cbbf4d36efa5
0000e9af7421452e8001a374085ca53b
000109e6bf54b3b20e8547b6026bc355
0001261e2060303a06ba6c64d676d639
000133296ef6b63b0210f224e1347365
000163671e7b29522ad47604f3b48cca
sh-4.4#
sh-4.4#

3.可能产生的问题
现象:

mysql> select id from pir_50w limit 10 into outfile './tmp/pir_50w_10.csv';
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

原因:mysql导入导出文件只能在secure-file-priv该变量配置的指定路径下的文件才可以导入导出。

解决方法:查看本地secure-file-priv变量配置

mysql> show variables like '%secure%';
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| require_secure_transport | OFF   |
| secure_file_priv         | /tmp/ |
+--------------------------+-------+
2 rows in set (0.01 sec)

mysql>

本次执行SQL导致报错的原因是into outfile './tmp/pir_50w_10.csv'路径出现错误,将./tmp前边的点去除即可。

posted @ 2023-06-25 16:21  大青橙子  阅读(731)  评论(0编辑  收藏  举报