使用shell操作mysql(转)

在linux平台下,为避免每次操作数据库(mysql)都要进入Mysql命令模式下,可以使用Shell命令直接操作数据库。

一、直接写sql语句

     if [ $# -ne 1 ]
     then
            echo "请输入要运行的sql语句"
            exit -1
     fi
     mysql -Dmysql -uroot -p123456abcd -e"$1"

  -D 指定数据库名称

  -u 指定数据库用户名

  -p 指定数据库密码

-e 指定要运行的sql语句

二、脚本方式运行

  if [ $# -ne 1 ]
  then
        echo "请输入要运行的sql语句"
        exit -1
  fi
  cat $1 | mysql -Dmysql -uroot -p123456abcd

  $1 指定要运行的sql语句脚本

三、示例

#!/bash/sh

HOSTNAME=”localhost”

USERNAME=”root”

PASSWORD=”root”

DBNAME=”student_db”

TABLENAME=”stu”

Show_db=”show database”

mysql –h${ HOSTNAME } –u ${ USERNAME }  -p${ PASSWORD } –e “${show_db}”

TABLENAME_NEW=${ TABLENAME }_’date “+%Y_%m_%d” ’

create_table_sql= “create table if not exists ${ TABLENAME_NEW } (id int(5) not null primary key)”

mysql –h${ HOSTNAME } –u ${ USERNAME }  -p${ PASSWORD } -D{DBNAME} –e “${ create_table_sql }”

if [ $? = 0 ]; then

  echo “create yes”

fi

 (转)http://www.cnblogs.com/chenchenluoxi/archive/2013/04/19/3029838.html

原文地址:https://www.cnblogs.com/llphhl/p/5696979.html