本文主要实现在shell脚本中操作mysql数据库执行sql语句,并且将执行的结果集保存到文本文件中,方便运维人员做自动化数据库备份等操作。
操作环境
[root@study scripts]# cat /etc/centos-release
CentOS release 6.10 (Final)
[root@study scripts]# mysql --version
mysql Ver 14.14 Distrib 5.7.23, for Linux (x86_64) using EditLine wrapper
知识点
mysql -u登录名 -p密码 -e 执行sql文件
1.SQL语句嵌入到shell脚本中
#!/bin/bash
# execute sql
mysql -uroot -p123456 -e "
use study;
select *from sys_user;
" >> user.txt
2.shell脚本执行SQL语句文件
- sql文件
use study;
select *from sys_user;
- shell脚本
#!/bin/bash
# execute sql
mysql -uroot -p123456 -e "source temp1.sql" >> 2.txt
3.管道符调用SQL文件
mysql -uroot -p123456 < temp1.sql >> 3.txt