当前位置:Gxlcms > 数据库问题 > Linux—编写shell脚本操作数据库执行sql

Linux—编写shell脚本操作数据库执行sql

时间:2021-07-01 10:21:17 帮助过:123人阅读

修改数据库数据

??在升级应用时,我们常常会遇到升级数据库的问题,这就涉及到sql脚本的编写。
??一般我们会通过写sql脚本,然后将xxx.sql脚本放到数据库中进行source xxx.sql执行。本篇文章,我们可以通过写shell脚本来执行数据库操作。

配置文件

创建 test_sql.properties 作为shell脚本的外部配置参数修改:

  1. <code>[andya@liunx01 sql_sh]$ vim test_sql.properties
  2. # set parameters start
  3. # 1 db name
  4. dbName="db01"
  5. # 2 the valueof net speeds and requests
  6. netMaxSpeeds=500
  7. netRequests="test.t1"
  8. # 3 database info
  9. ## mysql address
  10. MYSQL_ADDRESS="10.127.0.1"
  11. ## database name
  12. MYSQL_DATABASE_NAME="db_test"
  13. ## 5.3 bdoc connect mysql user name
  14. MYSQL_USER="user01"
  15. ## 5.4 bdoc connect mysql user password
  16. MYSQL_PASSWD="123456"
  17. ## 5.5 mysql engine
  18. DATABASE_ENGINE=mysql
  19. </code>

shell脚本

创建shell脚本test_sql.sh

  1. <code>[andya@liunx01 sql_sh]$ vim test_sql.sh
  2. #!/bin/bash
  3. starttime=$(date +%Y-%m-%d\ %H:%M:%S)
  4. echo "【Start to execute the script】, start time is: " $starttime >> test_sql_sh.log
  5. # 1 read parameters
  6. # ===================================================================
  7. echo "------ test_sql.properties start------" >> test_sql_sh.log
  8. source ./test_sql.properties
  9. echo "Parameters: cat test_sql.properties" >> test_sql_sh.log
  10. while read line
  11. do
  12. echo $line >> test_sql_sh.log ;
  13. done < test_sql.properties
  14. echo "------ test_sql.properties end------" >> test_sql_sh.log
  15. # =================================================================
  16. # 2 update database
  17. # ========================
  18. testSql="
  19. SET @dbId=(SELECT id FROM ${MYSQL_DATABASE_NAME}.\`test_tb01\` WHERE \`NAME\` = \"${dbName}\");
  20. INSERT INTO ${MYSQL_DATABASE_NAME}.\`test_tb02\` (\`NAME\`, \`DB_ID\` ,\`MAX_SPEEDS\`, \`NET_REQUESTS\`) VALUES ('${dbName}', @dbId, '${netMaxSpeeds}', '${netRequests}');
  21. "
  22. echo -e "\nSql: add hbase sql is: "${testSql} >> test_sql_sh.log
  23. id=$(${DATABASE_ENGINE} -h${MYSQL_ADDRESS} -u${MYSQL_USER} -p${MYSQL_PASSWD} -D ${MYSQL_DATABASE_NAME} -e "${testSql}")
  24. echo "Sql: Modify db data successfully, and insert db id is: "${id} >> test_sql_sh.log
  25. endtime=`date +"%Y-%m-%d %H:%M:%S"`
  26. echo "【Execute the script end】, end time is: " ${endtime} >> test_sql_sh.log
  27. echo -e "\n" >> test_sql_sh.log
  28. exit 0
  29. </code>

脚本执行

./test_sql.sh
并且可以查看到输出日志test_sql_sh.log

Linux—编写shell脚本操作数据库执行sql

标签:shell   code   echo   数据库   cat   数据库数据   insert   数据库操作   shel   

人气教程排行