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相关问答推荐

客户跨订阅的跨时间线计数

默认情况下,MariaDB是否限制为本地主机?

从insert语句获取新生成的虚拟UUID

是否可以使用 IN 或 NOT IN 从没有关联其他表中任何行的表中返回这些名称?

按年份范围 SQL 查询分组

当每组的列值发生变化时 Select 并连接行

无法通过迁移在现有表中插入行 - Rails 6

Over() 函数不覆盖表中的所有行

如果在表中多次发现 a 列中的相同值,则排除所有行

在 MySQL 中使用三个表进行计算

如何在 MySQL 中搜索多个列?

MySQL:将日期时间插入其他日期时间字段

如何为 php 启用 mysqlnd?

一次查询 MySQL 插入多行

MYSQL_ROOT_PASSWORD 已设置但在 docker 容器中获取用户'root'@'localhost'的访问被拒绝(使用密码:YES)

MySQL 实用程序 - ~/.my.cnf 选项文件

MySQL:ALTER IGNORE TABLE 给出违反完整性约束

如何使用 XML_LOAD() 将 XML 文件导入 MySQL 数据库表;功能

判断多个列的一个值

在 MySQL 的 LIMIT 子句中使用变量