首页 > 数据库 > mysql教程 > shell脚本操作mysql数据库

shell脚本操作mysql数据库

WBOY
发布: 2016-06-07 15:35:16
原创
1563 人浏览过

#!/bin/bash HOSTNAME=192.168.1.224 #数据库Server信息 PORT=3306 USERNAME=root PASSWORD=123456 DBNAME=test_db_name #要创建的数据库的库名称 TABLENAME=test_table_name #要创建的数据库的表的名称 MYSQL_CMD=mysql -h${HOSTNAME} -P${PORT} -u${USERNA

#!/bin/bash

HOSTNAME="192.168.1.224"                                           #数据库Server信息
PORT="3306"
USERNAME="root"
PASSWORD="123456"

 

DBNAME="test_db_name"                                              #要创建的数据库的库名称
TABLENAME="test_table_name"                                  #要创建的数据库的表的名称

 

MYSQL_CMD="mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD}"
echo ${MYSQL_CMD}

 

echo "create database ${DBNAME}"

create_db_sql="create database IF NOT EXISTS ${DBNAME}"
echo ${create_db_sql}  | ${MYSQL_CMD}                         #创建数据库                    
if [ $? -ne 0 ]                                                                                #判断是否创建成功
then
 echo "create databases ${DBNAME} failed ..."
 exit 1
fi


echo "create table ${TABLENAME}"

create_table_sql="create table ${TABLENAME}(
name char(6) NOT NULL,
id int default 0
)ENGINE=MyISAM DEFAULT CHARSET=latin1"
echo ${create_table_sql} | ${MYSQL_CMD} ${DBNAME}              #在给定的DB上,创建表
if [ $? -ne 0 ]                                                                                                #判断是否创建成功
then
 echo "create  table ${DBNAME}.${TABLENAME}  fail ..."
fi

http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201141142057473/


或者如下操作

#创建数据库
create_db_sql="create database IF NOT EXISTS ${DBNAME}"
mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD} -e "${create_db_sql}"

 

#创建表
create_table_sql="create table IF NOT EXISTS ${TABLENAME} (  name varchar(20), id int(11) default 0 )"
mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD} ${DBNAME} -e"${create_table_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${PORT}  -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}"

http://blog.csdn.net/xiaoxinghehe/article/details/8663085
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板