将 mysql 查询输出存储到 shell 变量中

2022-01-04 00:00:00 bash sql mysql scripting

我需要一个变量来保存从数据库中检索到的结果.到目前为止,这基本上是我正在尝试但没有成功的方法.

myvariable=$(mysql 数据库 -u $user -p $password | SELECT A, B, C FROM table_a)

如你所见,我对 bash 命令的理解不是很好.

解决方案

我对 MySQL 命令行界面了解不多,但假设您只需要帮助解决问题,您应该尝试交换命令,例如所以:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql 数据库 -u $user -p$password)

将字符串回显到 MySQL 中.或者,您可以更花哨并使用一些新的 bash 功能(此处的字符串)

myvariable=$(mysql 数据库 -u $user -p$password<<<"SELECT A, B, C FROM table_a")

导致同样的事情(假设您使用的是足够新的 bash 版本),而不涉及 echo.

请注意,-p$password 不是拼写错误,而是 MySQL 期望通过命令行输入密码的方式(选项和值之间没有空格).

请注意,myvariable 将包含 MySQL 在标准输出上输出的所有内容(通常除了错误消息之外的所有内容),包括任何和所有列标题、ASCII 艺术帧等,这些内容可能是您想要的,也可能不是.


如前所述,MySQL 似乎有一个 -e 参数,我肯定会选择那个.

I need a variable to hold results retrieved from the database. So far this is basically what I'm trying with no success.

myvariable=$(mysql database -u $user -p $password | SELECT A, B, C FROM table_a)

My understanding of bash commands is not very good as you can see.

解决方案

I don't know much about the MySQL command line interface, but assuming you only need help with the bashing, you should try to either swap the commands around like so:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)

which echos the string into MySQL. Or, you can be more fancy and use some new bash-features (the here string)

myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")

resulting in the same thing (assuming you're using a recent enough bash version), without involving echo.

Please note that the -p$password is not a typo, but is the way MySQL expects passwords to be entered through the command line (with no space between the option and value).

Note that myvariable will contain everything that MySQL outputs on standard out (usually everything but error messages), including any and all column headers, ASCII-art frames and so on, which may or may not be what you want.

EDIT:
As has been noted, there appears to be a -e parameter to MySQL, I'd go for that one, definitely.

相关文章