Linux命令行中进行调用SQL文件,总结如下:
1、命令行调用SQL文件
假设SQL文件为test.sql
1、SQL文件内容如下:
# more test.sql
tee /tmp/test.log
drop database if exists tempdb;
create database tempdb;
use tempdb;
create table if not exists tb_tmp(id smallint,val varchar(20));
insert into tb_tmp values (1,'jack'),(2,'robin'),(3,'mark');
select * from tb_tmp;
notee
2、然后在命令行中进行如下执行:
mysql -uroot -p123456 -e "source /root/test.sql"
Logging to file ‘/tmp/test.log’
±-----±------+
| id | val |
±-----±------+
| 1 | jack |
| 2 | robin |
| 3 | mark |
±-----±------+
Outfile disabled.
2、使用管道符调用SQL文件
假设SQL文件为:test.sql
1、命令行进行如下调用。【仅调用】
mysql -uroot -p123456 </root/temp.sql
Logging to file ‘/tmp/test.log’
id val
1 jack
2 robin
3 mark
Outfile disabled.
2、命令行进行调用。【并输出日志】
mysql -uroot -p123456 </root/temp.sql >/tmp/test.log
more /tmp/test.log
Logging to file ‘/tmp/test.log’
id val
1 jack
2 robin
3 mark
Outfile disabled.
3、shell脚本中变量输入与输出
假如我们需要在shell脚本中获得变量的输入与输出
方法一:
可进行如下操作:
1、假如脚本为:shell_test.sh
2、脚本内容为:
#!/bin/bash
cmd="select count(*) from tempdb.tb_tmp"
cnt=$(mysql -uroot -p123456 -s -e "${cmd}")
echo "Current count is : ${cnt}"
exit
3、然后命令行进行如下执行
./shell_call_sql3.sh
Current count is : 3
方法二:命令行进行获取
echo "select count(*) from tempdb.tb_tmp"|mysql -uroot -p123456 -s
输出结果:3