Shell脚本中执行sql语句操作mysql

时间:2023-02-26 10:07:51

对于自动化运维,诸如备份恢复之类的,DBA经常需要将SQL语句封装到shell脚本。本文描述了在Linux环境下mysql数据库中,shell脚本下调用sql语句的几种方法,供大家参考。对于脚本输出的结果美化,需要进一步完善和调整。以下为具体的示例及其方法。

1、将SQL语句直接嵌入到shell脚本文件中

复制代码 代码如下:
--演示环境  
[root@SZDB ~]# more /etc/issue  
CentOS release 5.9 (Final)  
Kernel \r on an \m  
  
root@localhost[(none)]> show variables like 'version';  
+---------------+------------+  
| Variable_name | Value      |  
+---------------+------------+  
| version       | 5.6.12-log |  
+---------------+------------+  
  
[root@SZDB ~]# more shell_call_sql1.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 -uroot -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@SZDB ~]# ./shell_call_sql1.sh   
Logging to file '/tmp/temp.log'  
+------+-------+  
| id   | val   |  
+------+-------+  
|    1 | jack  |  
|    2 | robin |  
|    3 | mark  |  
+------+-------+  
Outfile disabled.  

2、命令行调用单独的SQL文件

复制代码 代码如下:
[root@SZDB ~]# more 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,'jack'),(2,'robin'),(3,'mark');  
select * from tb_tmp;  
notee  
  
[root@SZDB ~]# mysql -uroot -p123456 -e "source /root/temp.sql"  
Logging to file '/tmp/temp.log'  
+------+-------+  
| id   | val   |  
+------+-------+  
|    1 | jack  |  
|    2 | robin |  
|    3 | mark  |  
+------+-------+  
Outfile disabled.  

3、使用管道符调用SQL文件

复制代码 代码如下:
[root@SZDB ~]# mysql -uroot -p123456 </root/temp.sql  
Logging to file '/tmp/temp.log'  
id      val  
1       jack  
2       robin  
3       mark  
Outfile disabled.  
  
#使用管道符调用SQL文件以及输出日志  
[root@SZDB ~]# mysql -uroot -p123456 </root/temp.sql >/tmp/temp.log  
[root@SZDB ~]# more /tmp/temp.log  
Logging to file '/tmp/temp.log'  
id      val  
1       jack  
2       robin  
3       mark  
Outfile disabled.  

4、shell脚本中MySQL提示符下调用SQL

复制代码 代码如下:
[root@SZDB ~]# more shell_call_sql2.sh  
#!/bin/bash  
mysql -uroot -p123456 <<EOF  
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@SZDB ~]# ./shell_call_sql2.sh  
Logging to file '/tmp/temp.log'  
id      val  
1       jack  
2       robin  
3       mark  
Outfile disabled.  
current_date()  
2014-10-14  
id      val  
2       robin  

5、shell脚本中变量输入与输出

复制代码 代码如下:
[root@SZDB ~]# more shell_call_sql3.sh  
#!/bin/bash  
cmd="select count(*) from tempdb.tb_tmp"  
cnt=$(mysql -uroot -p123456 -s -e "${cmd}")  
echo "Current count is : ${cnt}"  
exit   
[root@SZDB ~]# ./shell_call_sql3.sh   
Warning: Using a password on the command line interface can be insecure.  
Current count is : 3  
  
[root@SZDB ~]# echo "select count(*) from tempdb.tb_tmp"|mysql -uroot -p123456 -s  
3  
  
[root@SZDB ~]# more shell_call_sql4.sh  
#!/bin/bash  
id=1  
cmd="select count(*) from tempdb.tb_tmp where id=${id}"  
cnt=$(mysql -uroot -p123456 -s -e "${cmd}")  
echo "Current count is : ${cnt}"  
exit   
  
[root@SZDB ~]# ./shell_call_sql4.sh   
Current count is : 1   
 
 

下面附上通过shell命令行非交互式的操作数据库的方法:

mysql -hhostname -Pport -uusername -ppassword -e 相关mysql的sql语句,不用在mysql的提示符下运行mysql,即可以在shell中操作mysql的方法。

#!/bin/bash

HOSTNAME="192.168.111.84"  #数据库信息

PORT="3306"

USERNAME="root"

PASSWORD=""

DBNAME="test_db_test"  #数据库名称

TABLENAME="test_table_test" #数据库中表的名称

#创建数据库

create_db_sql="create database IF NOT EXISTS ${DBNAME}"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} -e "${create_db_sql}"

#创建表

create_table_sql="create table IF NOT EXISTS ${TABLENAME} ( name varchar(20), id int(11) default 0 )"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${create_table_sql}"

#插入数据

insert_sql="insert into ${TABLENAME} values('billchen',2)"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${insert_sql}"

#查询

select_sql="select * from ${TABLENAME}"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}"

#更新数据

update_sql="update ${TABLENAME} set id=3"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${update_sql}"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}"

#删除数据

delete_sql="delete from ${TABLENAME}"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${delete_sql}"

mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}"

Shell脚本中执行sql语句操作mysql的更多相关文章

  1. Shell脚本中执行sql语句操作mysql的5种方法【转】

    对于自动化运维,诸如备份恢复之类的,DBA经常需要将SQL语句封装到shell脚本.本文描述了在Linux环境下mysql数据库中,shell脚本下调用sql语句的几种方法,供大家参考.对于脚本输出的 ...

  2. SHELL脚本中执行SQL语句操作MYSQL的5种方法

    对于自动化运维,诸如备份恢复之类的,DBA经常需要将SQL语句封装到shell脚本.本文描述了在Linux环境下mysql数据库中,shell脚本下调用sql语句的几种方法,供大家参考.对于脚本输出的 ...

  3. shell 脚本中执行SQL语句 -e &quot&semi;&period;&period;&period;&quot&semi;

    /usr/local/mysql/bin/mysql -uroot -p123456 -e " use faygo source faygo.sql select * from devqui ...

  4. shell脚本中执行sql的例子

    这个例子演示了如何在shell脚本中执行多个sql来操作数据库表. #! /bin/sh USER_HOME=/home/`whoami` . /etc/profile if [ -f ${USER_ ...

  5. Shell脚本直接执行sql语句和不显示列名

    在shell脚本编程的时候,可以通过在mysql连接命令添加-N和-e参数实现查询结果不显示列名和直接执行sql语句操作 demo $(mysql -h ${HOST} -u ${USER} -p${ ...

  6. 如何在脚本中执行SQL语句并获得结果输出&quest;

    这里需要用到的工具叫做sqlcmd.exe, 它随SQL server的安装而安装. 该可执行程序的位置在: C:\Program Files\Microsoft SQL Server\xxx\Too ...

  7. shell脚本中执行sql命令

    1.mysql 数据库表信息 2.shell脚本(a.sh)信息 #!/bin/sh mysql -u root << myInsert insert into test.t values ...

  8. shell脚本中执行sql脚本并传递参数&lpar;mysql为例&rpar;

    1.mysql脚本文件 t.sql insert into test.t values(@name,@age); exit 2.shell脚本文件 a.sh  (为方便演示,与t.sql文件放在同一目 ...

  9. shell脚本中执行sql脚本&lpar;mysql为例&rpar;

    1.sql脚本(t.sql) insert into test.t value ("LH",88); 2.shell脚本(a.sh     为方便说明,a.sh与t.sql在同一目 ...

随机推荐

  1. ASP&period;NET导出文件FileResult的使用

    本文给大家讲一下ASP.NET MVC中如何使用FileResult来导出文件,首先网上相关例子有很多大神都有讲,我在这只是稍微说一点不同——为什么我的导出没有反应呢? 这个问题,我找了半天也没有找到 ...

  2. FFTW中文参考

    据说FFTW(Fastest Fourier Transform in the West)是世界上最快的FFT.为了详细了解FFTW以及为编程方便,特将用户手册看了一下,并结合手册制作了以下FFTW中 ...

  3. shopnc nginx优化配置文件

    user www; worker_processes 2; error_log /var/log/nginx/error.log error; #error_log logs/error.log no ...

  4. 转 linux目录介绍

    以下用一个表格来罗列linux默认的目录或文件及其用途: 目录/文件 用途 来源 / /处于Linux文件系统树形结构的最顶端,它是Linux文件系统的入口,所有的目录.文件.设备都在/之下. - / ...

  5. poi 导出excel 异常处理方式--曲线救国法

    excel 导出不算什么新鲜的话题.目前各种生成excel的开源jar包,poi,jxtl等.但是下载过程中如果出现异常该如何处理呢. 翻了之前的几个项目中的excel导出,有的异常就直接抛了出去,有 ...

  6. java多线程-消费者和生产者模式

    /* * 多线程-消费者和生产者模式 * 在实现消费者生产者模式的时候必须要具备两个前提,一是,必须访问的是一个共享资源,二是必须要有线程锁,且锁的是同一个对象 * */ /*资源类中定义了name( ...

  7. AD预测论文研读系列2

    EARLY PREDICTION OF ALZHEIMER'S DISEASE DEMENTIA BASED ON BASELINE HIPPOCAMPAL MRI AND 1-YEAR FOLLOW ...

  8. C&plus;&plus; 指针常量和常量指针

    1.指针常量(*const):对应指针变量,即指针本身是常量,指针指向的内容可以被修改. 2.常量指针(const*):常量的指针,即指针指向的内容不能被修改,但指针本身是变量,可以被修改.

  9. Ubuntu 实践

    Ubuntu 安装中文支持 开始装的是Ubuntu Server,后来需要某些图形工具,所以装了个Gnome,没想到无论如何都显示不了中文,按照网上的方法试了一堆,装了Synaptic,KDE和GNO ...

  10. 使用Sqlserver事务发布实现数据同步&lpar;sql2008&rpar;&lowbar;Mssq l数据库教程

    事务的功能在sqlserver中由来已久,因为最近在做一个数据同步方案,所以有机会再次研究一下它以及快照等,发现还是有很多不错的功能和改进的.这里以sqlserver2008的事务发布功能为例,对发布 ...