mysql - 在一段时间间隔后从 shell 脚本调用 MySQL 查询

标签 mysql windows bash shell mingw

我想在一段时间后从 shell 脚本执行 MySQL 查询。我已经编写了脚本,但输出不符合预期。它再次从数据库打印相同的值。有人可以帮忙吗?

SCRIPT- demo.sh

#!/bin/bash
echo "Shell Script to Query a Database!"
echo "--Querying from the Database starts--"
cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
for i in {1..5};
do 
./mysql -u root -proot@123 << EOF
use catalyst_latest;
select id from ci_master limit 1;
EOF
echo "Wait for 2 seconds for the next ID." 
sleep 2; 
done
echo "--Query Stopped!--"

输出

$ ./demo.sh
Shell Script to Query a Database!
--Querying from the Database starts--
mysql: [Warning] Using a password on the command line interface can be   insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
mysql: [Warning] Using a password on the command line interface can be insecure.
id
282
Wait for 2 seconds for the next ID.
--Query Stopped!--

你能看到每次都返回 282 吗?所以我想在 2 秒后从数据库中获取下一个 ID。请告诉我该怎么做。 预先感谢您。

最佳答案

您需要将返回的 id 值记住到 bash 变量中,然后在查询的 WHERE 子句中重用该变量,如下所示:

select id from ci_master where id > $id limit 1

要将命令的输出写入变量,请使用如下所示的内容:

id=$(mysql <options> -Nsqe "<query>")

选项N跳过列名(如id),选项s用于更静默的输出,选项q用于不缓存结果,选项e 表示要执行的命令。

最初,$id 变量应设置为某个值,例如 1 或表中现有值的最小值。

关于mysql - 在一段时间间隔后从 shell 脚本调用 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223632/

相关文章:

c++ - 传递给 CreateProcess 的参数未按我预期的那样进行解析

python - conda 托管环境中的 Shebang

mysql - 每 N 秒选择不超过 1 行

mysql - SELECT 仅由指定字母组成的单词

windows - VBScript 错误 - 使用用户名和密码创建 FTP 快捷方式

android - Windows 上的 Calabash-Android

linux - 如何在 bash shell 中将一个单词拆分为多个变量?

bash - 使用信号陷阱中断 bash 中的 sleep

MYSQL获取两个结果的差异

PHP-将带有复选框的多个类别添加到mysql中