MySQL篇之在Linux命令行中调用SQL文件的方法

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
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值