修改數據庫數據
在升級應用時,我們常常會遇到升級數據庫的問題,這就涉及到sql腳本的編寫。
一般我們會通過寫sql腳本,然后將xxx.sql腳本放到數據庫中進行source xxx.sql
執行。本篇文章,我們可以通過寫shell腳本來執行數據庫操作。
配置文件
創建 test_sql.properties 作為shell腳本的外部配置參數修改:
[andya@liunx01 sql_sh]$ vim test_sql.properties
# set parameters start
# 1 db name
dbName="db01"
# 2 the valueof net speeds and requests
netMaxSpeeds=500
netRequests="test.t1"
# 3 database info
## mysql address
MYSQL_ADDRESS="10.127.0.1"
## database name
MYSQL_DATABASE_NAME="db_test"
## 5.3 bdoc connect mysql user name
MYSQL_USER="user01"
## 5.4 bdoc connect mysql user password
MYSQL_PASSWD="123456"
## 5.5 mysql engine
DATABASE_ENGINE=mysql
shell腳本
創建shell腳本test_sql.sh
[andya@liunx01 sql_sh]$ vim test_sql.sh
#!/bin/bash
starttime=$(date +%Y-%m-%d\ %H:%M:%S)
echo "【Start to execute the script】, start time is: " $starttime >> test_sql_sh.log
# 1 read parameters
# ===================================================================
echo "------ test_sql.properties start------" >> test_sql_sh.log
source ./test_sql.properties
echo "Parameters: cat test_sql.properties" >> test_sql_sh.log
while read line
do
echo $line >> test_sql_sh.log ;
done < test_sql.properties
echo "------ test_sql.properties end------" >> test_sql_sh.log
# =================================================================
# 2 update database
# ========================
testSql="
SET @dbId=(SELECT id FROM ${MYSQL_DATABASE_NAME}.\`test_tb01\` WHERE \`NAME\` = \"${dbName}\");
INSERT INTO ${MYSQL_DATABASE_NAME}.\`test_tb02\` (\`NAME\`, \`DB_ID\` ,\`MAX_SPEEDS\`, \`NET_REQUESTS\`) VALUES ('${dbName}', @dbId, '${netMaxSpeeds}', '${netRequests}');
"
echo -e "\nSql: add hbase sql is: "${testSql} >> test_sql_sh.log
id=$(${DATABASE_ENGINE} -h${MYSQL_ADDRESS} -u${MYSQL_USER} -p${MYSQL_PASSWD} -D ${MYSQL_DATABASE_NAME} -e "${testSql}")
echo "Sql: Modify db data successfully, and insert db id is: "${id} >> test_sql_sh.log
endtime=`date +"%Y-%m-%d %H:%M:%S"`
echo "【Execute the script end】, end time is: " ${endtime} >> test_sql_sh.log
echo -e "\n" >> test_sql_sh.log
exit 0
腳本執行
./test_sql.sh
並且可以查看到輸出日志test_sql_sh.log
另一種連接方式(待研究)
#!/bin/sh
mysql_engine=`which mysql`
${mysql_engine} -uroot -p123456 <<EOF 1>>test.log
use db01;
select * from tb01 where id = 4;
EOF
exit 0
其中:
1)1>>test.log
是重定向標准輸出到test.log中,當然,也嘗試去掉1,也是可以輸出。
2)我們也可以使用2 >/dev/null
重定向來屏蔽錯誤信息,2即為標准錯誤輸出,對於linux來說/dev/null
即為空設備,輸入進去的數據即為丟棄。
3)EOF表示后續輸入作為shell的輸入,直到下一個EOF出現,再返回主進程shell中。