【问题标题】:How can I execute an SQL file, and save the results to a txt file in one command?如何执行 SQL 文件,并在一个命令中将结果保存到 txt 文件?
【发布时间】:2016-04-02 02:12:32
【问题描述】:

我正在使用 Ubuntu 终端。我找到了有关运行 .sql 文件以及如何将查询结果保存到外部文件的答案。我怎样才能同时做这两个?

我试过这个命令:source /path/to/file.sql into outfile /path/to/outfile.txt。

我尝试将into outfile /path/to/outfile.txt 直接添加到file.sql 并运行source /path/to/outfile.sql。

我已经尝试过mysql -u <username> -p <database> file.sql > results.txt.,如果我用类似-e "select * from myTable" 的东西切换file.sql,那么它工作正常。

我该怎么做?

编辑:这里是file.sql

select myID from Players where score > 80;

这是一个简单的查询,但如果我能解决这个问题,我可以尝试做更大的查询。

【问题讨论】:

标签: mysql


【解决方案1】:

你的答案在这里:http://dev.mysql.com/doc/refman/5.7/en/mysql.html

您可以像这样在脚本文件(批处理文件)中执行 SQL 语句:

shell> mysql db_name output.tab

试试这个:mysql -u username -p database < file.sql > results.txt

【讨论】:

    【解决方案2】:
    mysql -u root -p -e"`cat /path/to/file.sql`" > result.txt
    

    【讨论】:

    • 请添加一些解释。
    【解决方案3】:

    @FLefèvre 有一个解决方案,但我无法让它发挥作用。它只是输出了一个 MySQL 帮助页面,其中显示了不同的命令。

    将此添加到 sql 文件中:.... into outfile '/path/to/outfile.txt'。路径上的单引号或双引号。然后在 MySQL shell 中,执行source /path/to/file.sql。

    【讨论】:

    • 我的答案有效我测试了它。您的解决方案存在的问题是每次要更改结果文件时都需要修改文件内容。如果你从不重复使用它当然不是问题...... :)
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2011-07-16
    • 2021-02-01
    • 2022-06-16
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多