我需要一个变量来保存从数据库中检索到的结果.到目前为止,这基本上是我一直没有成功的尝试.
myvariable=$(mysql database -u $user -p $password | SELECT A, B, C FROM table_a)如您所见,我对bash命令的理解不是很好.
解决方案我对MySQL命令行界面了解不多,但是假设您只需要帮助,可以尝试像这样交换命令所以:
myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)将字符串回显到MySQL.或者,您可能会更喜欢并使用一些新的bash功能(here字符串)
myvariable=$(mysql database -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.
更多推荐
将mysql查询输出存储到shell变量中
发布评论