shell脚本中导入mysql数据&&执行mysql语句
2015-12-17 16:12
791 查看
http://blog.csdn.net/white__cat/article/details/27836481
前言
在线下做mysql数据分析的时候,会遇到执行shell脚本里导入sql文件到mysql数据库里或者连接mysql执行指定sql语句的情况,这里介绍一下我采用的方法
导入sql文件到mysql数据库
示例代码
[html] viewplaincopy
#变量定义
sqlname="test.sql"
dir="/sdb2/backup/mysql_db_backup/backup/databases"
host="127.0.0.1"
user="root"
passwd="123456"
dbname="test"
#导入sql文件到指定数据库
mysql -h$host -u$user -p$passwd $dbname < $dir/$sqlname
关键点
"<"运算符的使用
执行指定的sql语句
mysql的-e参数
参数解释
[html] viewplaincopy
--execute=statement, -e statement
xecute the statement and quit. The default output format is like that produced with --batch
[html] view
plaincopy
--silent, -s
Silent mode. Produce less output. This option can be given multiple times to produce less and less output.
示例代码
[html] viewplaincopy
select_sql="select count(distinct id) from tb_test"
num=$(mysql -s -h$host -u$user -p$passwd $dbname -e "$register_sql")
注意:
-s参数的使用是减少查询字段的输出(ps:我这里只需要查询的结果值,并不需要查询的字段名,不加-s参数会输出查询的字段名)
管道运算符
[html] viewplaincopy
echo "select count(distinct id) from tb_test" | mysql -h$host -u$user -p$passwd $dbname
ps:我建议使用-e参数,更加方便吧
mysqldump导出mysql数据
导出指定条件的数据库
命令格式
[html] viewplaincopy
mysqldump -u用户名 -p密码 -h主机 数据库名 表名 --where "sql语句"> 路径
示例代码
[html] viewplaincopy
#!/bin/bash
#变量定义
host="127.0.0.1"
user="root"
passwd="123456"
dbname="test"
tablename="tb_test"
mysqldump -u$user -p$passwd -h$host $dbname $tablename --where "id > 1 and id < 1000" > 1.sql
导出一个数据结构(无数据)
参数
[html] viewplaincopy
--no-data, -d
Do not write any table row information (that is, do not dump table contents). This is useful if you want to dump only the CREATE TABLE statement for the table (for example, to create an empty copy of the table by loading the dump file).
命令格式
[html] viewplaincopy
mysqldump -u用户名 -p密码 -h主机 数据库名 -d > 路径
示例代码
[html] viewplaincopy
#!/bin/bash
#变量定义
host="127.0.0.1"
user="root"
passwd="123456"
dbname="test"
mysqldump -u$user -p$passwd -h$host $dbname -d > 2.sql
参考链接
http://blog.linezing.com/2012/02/mysql%E5%AF%BC%E5%85%A5%E5%AF%BC%E5%87%BA%E6%95%B0%E6%8D%
相关文章推荐
- linux在shell中获取时间
- bash: useradd: command not found
- shell重定向调试信息
- 使用shell批处理进行不同参数运算
- shell小记:let
- bash的操作环境[转]
- 关于bash和dash
- Xshell使用教程及WinSCP使用教程
- shell脚本报错:-bash: xxx: /bin/sh^M: bad interpreter: No such file or directory
- Shell变量:Shell变量的定义、删除变量、只读变量、变量类型
- Linux下Shell编程解析
- Linux下Shell编程解析
- Shell 编程快速入门
- shell 命令之 find命令二
- shell 命令之 find 命令一
- .bash_profile和.bashrc的区别
- shell入门
- 利用joomla 3.2.0 – 3.4.4 注入漏洞到getshell
- Shell 编程快速入门
- Linux下Shell编程解析