将 mysql 查询结果输出到文件

直接用 mysql 命令
# 连接本地数据库,用户名为 gino 密码为 123456 指定所连接的数据库为 mysql
gino@gino-exploit:~$ mysql -h localhost -ugino -p123456 -D mysql  

# select 语句的结果输出到 /tmp 目录下的文件 user.xls
mysql> select host,user,password from user into outfile '/tmp/user.txt';

如果报错一下错,说明当前登录用户没有导出文件的权限,添加权限grant file on test.* to "user"@"%";

ERROR 1227 (42000): Access denied; you need (at least one of) the FILE privilege(s) for this operation

添加权限如果报以下错,提示该权限是global,必须使用*.* 方式

ERROR 1221 (HY000): Incorrect usage of DB GRANT and GLOBAL PRIVILEGES

换成grant file on *.* to "user"@"%";

然后在执行导出语句select host,user,password from user into outfile '/tmp/user.txt';

如果提示以下错误,说明不能导出指定的目录,mysql文件的导入和导出路径有默认的设置

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

可以使用以下命令来查看导入导出默认路径

show variables like '%secure%';

修改导出时的路径为默认路径即可导入导出。或者修改配置文件vim /etc/my.cnf

secure-file-priv的值有三种情况:

secure_file_prive=null          限制mysqld 不允许导入导出

secure_file_priv=/path/        限制mysqld的导入导出只能发生在默认的/path/目录下

secure_file_priv=''               不对mysqld 的导入 导出做限制

 

 


设置查询都结果都自动写入文件
mysql> pager cat > /tmp/test.txt
PAGER set to 'cat > /tmp/test.txt'
mysql> select host,user,password from user;
查询结果输出到 test.txt 文件中,取消写入,执行 pager 命令
mysql> pager 
Default pager wasn't set, using stdout.
mysql> select host from user;
+--------------+
| host         |
+--------------+
| %            |
| 127.0.0.1    |
| ::1          |
| gino-exploit |
| localhost    |
| localhost    |
+--------------+
6 rows in set (0.00 sec)
注意: pager cat >  这里用的是 “>”  不是追加( >> ) ,写入多条结果只会保存最后一条,如果要保存多条,用追加。

在 shell 命令行执行 mysql 语句,查询结果写入文件
第一种格式
gino@gino-exploit:~$ mysql -h localhost -ugino -p123456 -D mysql -e "select host,user,password from user" > /tmp/sh.txt

第二种格式
gino@gino-exploit:~$ mysql -h localhost -ugino -p123456 < t.sql  > /tmp/sql.txt
t.sql 的内容如下
gino@gino-exploit:~$ cat t.sql 
use mysql;
select host,user,password from user;

第三种格式
mysql -h localhost -ugino -p123456 -e "source t.sql" > /tmp/sousql.txt


推荐使用第一种格式,曾做过一个项目,因为数据库服务器的某些配置的原因,同样的查询语句(查询结果为395行),使用第一种方式生成的文件内容是396行(多一样是会将select语句后面的字段写在文件第一行)完整的,使用第二种方式生成的文件内容加上select语句后面的字段只有25行

posted @   silentmuh  阅读(1841)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
Live2D
欢迎阅读『将 mysql 查询结果输出到文件』
  1. 1 Walk Thru Fire Vicetone
  2. 2 爱你 王心凌
  3. 3 Inspire Capo Productions - Serenity
  4. 4 Welcome Home Radical Face
  5. 5 粉红色的回忆 李玲玉
Inspire - Capo Productions - Serenity
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

纯音乐,请欣赏

点击右上角即可分享
微信分享提示