网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Shell脚本中执行sql语句操作MySQL数据库的几个方法

实验如下:
[root@idb1 ~]# more /etc/issue
CentOS release 6.5 (Final)
Kernel \r on an \m


MySQL> show variables like 'version';
+---------------+------------+
| Variable_name | Value      |
+---------------+------------+
| version       | 5.6.27-log |
+---------------+------------+
1 row in set (0.00 sec)


1、将SQL语句直接嵌入到shell脚本文件中
[root@idb1 ~]# cat shell_example01.sh
#!/bin/bash
# Define log
TIMESTAMP=`date +%Y%m%d%H%M%S`
LOG=call_sql_${TIMESTAMP}.log
echo "Start execute sql statement at `date`." >>${LOG}

# execute sql stat
mysql -umdba -p123456 -e "
tee /tmp/temp.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
quit

echo -e "\n">>${LOG}
echo "below is output result.">>${LOG}
cat /tmp/temp.log>>${LOG}
echo "script executed successful.">>${LOG}
exit;

[root@idb1 ~]# chmod +x shell_example01.sh

[root@idb1 ~]# sh shell_example01.sh
Warning: Using a password on the command line interface can be insecure.
Logging to file '/tmp/temp.log'
+------+-------+
| id   | val   |
+------+-------+
|    1 | jack  |
|    2 | robin |
|    3 | mark  |
+------+-------+
Outfile disabled.


2、命令行调用单独的SQL文件例子:
[root@idb1 ~]# cat temp.sql
tee /tmp/temp.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,'duansf'),(2,'liuyb'),(3,'jack');
select * from tb_tmp;
notee
quit

[root@idb1 ~]# mysql -umdba -p -e "source /root/temp.sql"
Enter password:
Logging to file '/tmp/temp.log'
+------+--------+
| id   | val    |
+------+--------+
|    1 | duansf |
|    2 | liuyb  |
|    3 | jack   |
+------+--------+
Outfile disabled.

#使用管道符调用SQL文件以及输出日志
[root@idb1 ~]# mysql -umdba -p Enter password:
Logging to file '/tmp/temp.log'
id      val
1       duansf
2       liuyb
3       jack
Outfile disabled.


4、shell脚本中MySQL提示符下调用SQL命令例子:
[root@idb1 ~]# cat shell_example02.sh
#!/bin/bash
mysql -umdba -pdsf0723 <source /root/temp.sql;
select current_date();
delete from tempdb.tb_tmp where id=3;
select * from tempdb.tb_tmp where id=2;
EOF
exit


[root@idb1 ~]# sh shell_example02.sh
Warning: Using a password on the command line interface can be insecure.
Logging to file '/tmp/temp.log'
id      val
1       duansf
2       liuyb
3       jack
Outfile disabled.
current_date()
2017-03-14
id      val
2       liuyb

网站栏目:Shell脚本中执行sql语句操作MySQL数据库的几个方法
当前URL:http://bjjierui.cn/article/ihgidg.html

其他资讯