2013-02-07 123 views
0

这是我的问题。我有一组SQL数据库查询,我使用shell脚本和扩展名为.sql的相应批处理文件触发。我的一些查询需要一些手动用户输入(根据请求),我没有在我的脚本中实现。在MYSQL中接受用户输入? Shell脚本/批处理文件

截至目前,我采取在用户输入作为通过壳脚本日期:

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
mysql -u user -ppass < batch_file.sql 

我想可变$input传递给批处理文件。

与正在执行的SQL查询批处理文件看起来是这样的:

select count(*) as count from subscriptions 
where date_add(optin_date, interval 1 year) between "$input" 
and date(curdate()) 
and active = 1 
and stype = "domain"; 

哪里"$input"从shell脚本传下来的变量。

任何想法将欣赏,谢谢。在脚本中使用这里-DOC

回答

1

尝试这样做:

#!/bin/sh 

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
mysql -u user -ppass <<EOF 
select count(*) as count from subscriptions 
where date_add(optin_date, interval 1 year) between "$input" 
and date(curdatE()) 
and active = 1 
and stype = "domain"; 
EOF 

另一种解决方法,如果你不能使用任何原因,第一个解决方案:

echo "Please specify the date in yyyy-mm-dd format: 'input;" 
read input 
sed -i "s/\"\$input\"/$input/g" batch_file.sql 
mysql -u user -ppass < batch_file.sql 

更好地利用的东西如%%PATTERN%%而不是$input在SQL文件中进行替换,如果您更喜欢第二种解决方案。

+0

第一个解决方案只允许一次运行一个命令,因此是批处理文件。 第二种解决方案很有意义,但它没有检测到变量。 – KamilS

+0

您可以使用'&'(fork)在后台运行here-docs,因此您可以运行SQL批处理的N个实例。 –

+0

此外,只需检查,第一个解决方案不起作用。 '$ input'变量没有被识别。 – KamilS