阶段总结 ———— shell如何访问mysql

还是之前的项目,需要一个脚本管理mysql,

本来是用C写了一个,因为当时对于shell一头雾水啊,后来发现C相对于shell还是不方便,

毕竟shell改起来超快超简单啊啊啊啊啊,最后愣是自学shell,现学现卖把这个活儿搞定了,

哈哈哈,成功的锻炼了自己的自学能力,

下面就简单举个例子,让大家看看怎么用shell来操作mysql,

免得大家再去踩地雷,走弯路,

下面这段例子是查询mysql中mysql数据库的user表的host,user,password;

代码如下,有什么问题,欢迎大家留言,大家一起讨论学习:


#!/bin/bash

#there maybe some special words in mysql
#for example, Usage/Lock.....
#if you want search or operate it
#you should use like this 
#  select \`${sqpcial_words}\` from ......

DB_NAME="mysql"
DB_USER="root"
DB_PASSWORD="12345"
DB_PASSWORD_LEN=""
TB_NAME="user"
SQL_CMD=""
SQL_RESULT=""
SQL_RESULT_LEN=""



SQL_CMD="select host,user,password from ${TB_NAME}"
#echo ${SQL_CMD}
DB_PASSWORD_LEN=${#DB_PASSWORD}
if [[ ${DB_PASSWORD_LEN} -eq 0 ]];then
	SQL_RESULT=$(mysql -u${DB_USER} -D${DB_NAME} -e "${SQL_CMD}" --skip-column-name)  #filter the column names in the result
else
	SQL_RESULT=$(mysql -u${DB_USER} -p${DB_PASSWORD} -D${DB_NAME} -e "${SQL_CMD}" --skip-column-name)
fi

SQL_RESULT_LEN=${#DB_PASSWORD}
if [[ ${SQL_RESULT_LEN} -eq 0 ]];then
	echo "User Not Found !"
else
	echo "${SQL_RESULT}"	#you can do some others operations, not only 'echo'
fi




你可能感兴趣的:(shell)