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

时间:2017-02-14 10:26:04

标签: 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。请告诉我怎么做。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您需要将返回的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或表中现有值的最小值。

答案 1 :(得分:0)

#!/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..10};
do 
temp=`./mysql -u root -proot@123 << EOF
use catalyst_latest;
select id from ci_master limit $i;
EOF`
result=''
for j in $temp 
do 
result=$j
done
#date;
echo "$result"
echo "Wait for 1 seconds for the next ID." 
sleep 1; 
done
echo "--Query Stopped!--"