首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一段时间间隔后从shell脚本调用MySQL查询

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

Stack Overflow用户
提问于 2017-02-14 10:26:03
回答 2查看 426关注 0票数 0

一段时间后,我想从一个shell脚本中执行一个MySQL查询。我已经编写了脚本,但是输出并不像预期的那样。它将再次从数据库中打印相同的值。有人能帮忙吗。

脚本- demo.sh

代码语言:javascript
复制
#!/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!--"

输出

代码语言:javascript
复制
$ ./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。请告诉我怎么做。提前谢谢你。

EN

回答 2

Stack Overflow用户

发布于 2017-02-14 10:42:14

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

代码语言:javascript
复制
select id from ci_master where id > $id limit 1

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

代码语言:javascript
复制
id=$(mysql <options> -Nsqe "<query>")

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

最初,应该将$id变量设置为一些值,如1或表中现有值的最小值。

票数 1
EN

Stack Overflow用户

发布于 2017-02-15 07:10:23

代码语言:javascript
复制
#!/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!--"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42223632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档