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

编程入门 行业动态 更新时间:2024-10-21 03:39:10
本文介绍了将mysql查询输出存储到shell变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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变量中

本文发布于:2023-10-18 11:03:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504051.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   mysql   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!