如何从命令行通过 mysql 运行单个查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1602904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:20:16  来源:igfitidea点击:

How do you run a single query through mysql from the command line?

sqlmysqlunixcommand-line

提问by Matthew

I'm looking to be able to run a single query on a remote server in a scripted task.

我希望能够在脚本任务中在远程服务器上运行单个查询。

For example, intuitively, I would imagine it would go something like:

例如,直觉上,我想它会是这样的:

mysql -uroot -p -hslavedb.mydomain.com mydb_production "select * from users;"

回答by RC.

mysql -u <user> -p -e "select * from schema.table"

回答by John Kugelman

mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"

From the usage printout:

从用法打印输出:

-e, --execute=name
Execute command and quit. (Disables --forceand history file)

-e,--execute=name
执行命令并退出。(禁用--force和历史文件)

回答by ???u

here's how you can do it with a cool shell trick:

下面是如何用一个很酷的 shell 技巧来做到这一点:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

'<<<' 指示 shell 将其后的任何内容作为 stdin,类似于来自 echo 的管道。

use the -t flag to enable table-format output

使用 -t 标志启用表格式输出

回答by dnagirl

If it's a query you run often, you can store it in a file. Then any time you want to run it:

如果它是您经常运行的查询,则可以将其存储在文件中。然后任何时候你想运行它

mysql < thefile

(with all the login and database flags of course)

(当然还有所有登录和数据库标志)

回答by Oct

echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production