1. 程式人生 > >Shell指令碼中執行sql語句操作mysql

Shell指令碼中執行sql語句操作mysql


--演示環境 
[[email protected] ~]# more /etc/issue 
CentOS release 5.9 (Final) 
Kernel \r on an \m 
 
[email protected][(none)]> show variables like 'version'; 
+---------------+------------+ 
| Variable_name | Value      | 
+---------------+------------+ 
| version       | 5.6.12-log | 
+---------------+------------+ 
 
[
[email protected]
~]# 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; 
 
[[email protected] ~]# ./shell_call_sql1.sh  
Logging to file '/tmp/temp.log' 
+------+-------+ 
| id   | val   | 
+------+-------+ 
|    1 | jack  | 
|    2 | robin | 
|    3 | mark  | 
+------+-------+ 
Outfile disabled.