shell脚本操作mysql数据库

2年前 (2016-03-31) admin mysql 0评论 已收录 578℃
 shell 脚本操作mysql数据库--创建数据库,在该数据库中建表(插入,查询更新,删除操作)
#!/bin/bash
####数据库Server信息#####
HOSTNAM="192.168.2.100"
PORT="3306"
USERNAME="root"
PASSWORD="123"
##要创建的数据库名称###
DBNAME="test_db_name"
###要创建数据库表的名称###
TABLENAME="test_table_name"
MYSQL_CMD="mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD}"
echo ${MYSQL_CDN}
echo "creat database ${DBNAME}"
########创建数据库#########
create_db_sql="create database IF NOT EXISTS ${DBNAME}"
echo ${create_db_sql} | ${MYSQL_CMD}
if [$? -ne 0]
  then
     echo"creat database ${DBNAME}failed..."
     exit 1
fi
echo "creat table ${TABLENAME}"
creat_table_sql="creat table ${TABLENAME}(name char(6) NOT NULL,
id int default 0)ENGINE=MYISAM DEFAULT CHARSET=latin1"
echo ${creat_table_sql} | ${MYSQL_CMD}${DBNAME}
if [$? -ne 0]
 then
   echo"creat table ${DBNAME}.${TABLENAME}fail..."
fi
创建数据库中的exists exists (sql 返回结果集为真)
                     not exists (sql 不返回结果集为真)
##########插入数据##########
insert_sql="insert into ${TABLENAME} values('billchen',2)"
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${insert_sql}"
########查询##########
select_sql="select * from ${TABLENAME}"
mysql -h${HOSTNAME} -P${POST} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${select_sql}"
#######更新数据##########
update_sql="update ${TABLENAME} set id=3"
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${update_sql}"
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${select_sql}"
#####删除数据##########
delete_sql="delete from ${TABLENAME}"
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e${delete_sql}
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e${select_sql}
博主

让学习成为习惯,坚持-共享-开源-自由! 成功者决不放弃,放弃者绝不成功!

相关推荐

嗨、骚年、快来消灭0回复。