mysql -e详解
可以用shell脚本操作mysql数据库,使用mysql的-e参数可以执行各种sql的(创建,删除,增,删,改、查)等各种操作 。
mysql -hhostname -Pport -uusername -ppassword -e 相关mysql的sql语句,不用在mysql的提示符下运行mysql,即可以在shell中操作mysql的方法。
实例:
#!/bin/bash
HOSTNAME="192.168.111.84" #数据库信息
PORT="3306"
USERNAME="root"
PASSWORD=""
DBNAME="test_db_test" #数据库名称
TABLENAME="test_table_test" #数据库中表的名称
#创建数据库
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}"
mysql -e中 v的作用
用 mysql -e 生成结果导入指定文件时:● 若要同时显示语句本身:-v
● 若要增加查询结果行数:-vv
● 若要增加执行时间:-vvv
在一些监控脚本中可以用来简化代码
[plain] view plaincopyprint?- ㈠ 不带 v 测试:
- [mysql@even ~]$ mysql -uroot -poracle -e "SELECT VERSION();SELECT NOW()" > /home/mysql/test.sql
- [mysql@even ~]$ cat /home/mysql/test.sql
- VERSION()
- 5.5.16-log
- NOW()
- 2013-05-08 18:06:35
- ㈡ 带一个 v 测试:
- [mysql@even ~]$ mysql -uroot -poracle -e "SELECT VERSION();SELECT NOW()" -v > /home/mysql/test02.sql
- [mysql@even ~]$ cat /home/mysql/test02.sql
- --------------
- SELECT VERSION()
- --------------
- VERSION()
- 5.5.16-log
- --------------
- SELECT NOW()
- --------------
- NOW()
- 2013-05-08 18:08:40
- ㈢ 带两个 v 测试:
- [mysql@even ~]$ mysql -uroot -poracle -e "SELECT VERSION();SELECT NOW()" -vv > /home/mysql/test03.sql
- [mysql@even ~]$ cat /home/mysql/test03.sql
- --------------
- SELECT VERSION()
- --------------
- VERSION()
- 5.5.16-log
- 1 row in set
- --------------
- SELECT NOW()
- --------------
- NOW()
- 2013-05-08 18:14:05
- 1 row in set
- Bye
- ㈢ 带三个 v 测试:
- [mysql@even ~]$ mysql -uroot -poracle -e "SELECT VERSION();SELECT NOW()" -vvv > /home/mysql/test04.sql
- [mysql@even ~]$ cat /home/mysql/test04.sql
- --------------
- SELECT VERSION()
- --------------
- +------------+
- | VERSION() |
- +------------+
- | 5.5.16-log |
- +------------+
- 1 row in set (0.00 sec)
- --------------
- SELECT NOW()
- --------------
- +---------------------+
- | NOW() |
- +---------------------+
- | 2013-05-08 18:14:49 |
- +---------------------+
- 1 row in set (0.00 sec)
- Bye