mysql - MYSQL 接受用户输入? Shell 脚本/批处理文件

标签 mysql database shell user-input

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

到目前为止,我通过 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脚本传递下来的变量。

如有任何想法,我们将不胜感激,谢谢。

最佳答案

尝试在脚本中使用here-doc来执行此操作:

#!/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

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

关于mysql - MYSQL 接受用户输入? Shell 脚本/批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753721/

相关文章:

MySQL 解释与慢日志

MySQL假设基于多值插入和第一个id自动递增ID

php - 数据库对象不工作 (PHP) : "Call to a member function query() on a non-object"

linux - 创建特定类型的文件

shell - Emacs 在当前窗口打开另一个 shell

java - 有没有办法根据参数值使 MySQL 查询行为不同?

php - 使用PHPExcel将excel文件内容导入MySQL数据库(格式问题)

sql-server - SQL Server更新语句执行

Mysql 无法添加外键约束。我该如何解决它?

linux - "Ambiguous output redirect"尝试从发送到 at 的命令将 stdout 和 stderr 发送到 mailx