shell脚本中导入mysql数据&&执行mysql语句

http://blog.csdn.net/white__cat/article/details/27836481

前言

在线下做mysql数据分析的时候,会遇到执行shell脚本里导入sql文件到mysql数据库里或者连接mysql执行指定sql语句的情况,这里介绍一下我采用的方法


导入sql文件到mysql数据库


示例代码

[html]  view plain copy
  1. #变量定义  
  2. sqlname="test.sql"  
  3. dir="/sdb2/backup/mysql_db_backup/backup/databases"  
  4. host="127.0.0.1"  
  5. user="root"  
  6. passwd="123456"  
  7. dbname="test"  
  8.   
  9.   
  10. #导入sql文件到指定数据库  
  11. mysql -h$host -u$user -p$passwd $dbname < $dir/$sqlname  

关键点

"<"运算符的使用


执行指定的sql语句


mysql的-e参数


参数解释
[html]  view plain copy
  1. --execute=statement, -e statement  
  2. xecute the statement and quit. The default output format is like that produced with --batch  
[html]  view plain copy
  1. --silent, -s  
  2. Silent mode. Produce less output. This option can be given multiple times to produce less and less output.  

示例代码
[html]  view plain copy
  1. select_sql="select count(distinct id) from tb_test"  
  2. num=$(mysql -s -h$host -u$user -p$passwd $dbname -e "$register_sql")  

注意:
  • -s参数的使用是减少查询字段的输出(ps:我这里只需要查询的结果值,并不需要查询的字段名,不加-s参数会输出查询的字段名)

管道运算符

[html]  view plain copy
  1. echo "select count(distinct id) from tb_test" | mysql -h$host -u$user -p$passwd $dbname  

ps:我建议使用-e参数,更加方便吧


mysqldump导出mysql数据


导出指定条件的数据库

命令格式
[html]  view plain copy
  1. mysqldump -u用户名 -p密码 -h主机  数据库名 表名  --where "sql语句"> 路径  
示例代码
[html]  view plain copy
  1. #!/bin/bash  
  2. #变量定义  
  3. host="127.0.0.1"  
  4. user="root"  
  5. passwd="123456"  
  6. dbname="test"  
  7. tablename="tb_test"  
  8. mysqldump -u$user -p$passwd -h$host $dbname  $tablename --where "id > 1 and id < 1000"  > 1.sql  


导出一个数据结构(无数据)

参数
[html]  view plain copy
  1. --no-data, -d  
  2. 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]  view plain copy
  1. mysqldump -u用户名 -p密码 -h主机 数据库名 -d > 路径  

示例代码
[html]  view plain copy
  1. #!/bin/bash  
  2.   
  3.   
  4. #变量定义  
  5. host="127.0.0.1"  
  6. user="root"  
  7. passwd="123456"  
  8. dbname="test"  
  9.   
  10. mysqldump -u$user -p$passwd -h$host $dbname -d > 2.sql  


参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值