Shell 指令碼中執行MySQL語句

來源:互聯網
上載者:User

Shell 指令碼中執行MySQL語句

對於自動化營運,諸如備份恢複之類的,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.
--Author : Leshami
--Blog  :

《MySQL權威指南(原書第2版)》清晰中文掃描版 PDF

Ubuntu 14.04 LTS 安裝 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主從伺服器

Ubuntu 12.04 LTS 構建高可用分布式 MySQL 叢集

Ubuntu 12.04下原始碼安裝MySQL5.6以及Python-MySQLdb

MySQL-5.5.38通用二進位安裝

--------------------------------------分割線 --------------------------------------

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.