shell处理mysql增、删、改、查
2015-04-30 09:31
316 查看
shell处理mysql增、删、改、查
引言
这几天做一个任务,比对两个数据表中的数据,昨天用PHP写了一个版本,但考虑到有的机器没有php或者php没有编译mysql扩展,就无法使用mysql系列的函数,脚本就无效了,今天写个shell版本的,这样,在所有linux系列机器上就都可以运行了。shell是如何操作mysql的?
shell操作mysql其实就是通过mysql命令通过参数去执行语句,跟其他程序里面是一样的,看看下面这个参数:-e, --execute=name Execute command and quit. (Disables --force and history file.)
因此我们可以通过mysql -e来执行语句,就像下面这样:
mysql -hlocalhost -P3306 -uroot -p123456 $test --default-character-set=utf8 -e "select * from users"
执行之后返回下面结果:
在shell脚本中操作mysql
导出数据
MYSQL="mysql -h192.168.1.102 -uroot -p123456 --default-character-set=utf8 -A -N" #这里面有两个参数,-A、-N,-A的含义是不去预读全部数据表信息,这样可以解决在数据表很多的时候卡死的问题 #-N,很简单,Don't write column names in results,获取的数据信息省去列名称 sql="select * from test.user" result="$($MYSQL -e "$sql")" dump_data=./data.user.txt >$dump_data echo -e "$result" > $dump_data #这里要额外注意,echo -e "$result" > $dump_data的时候一定要加上双引号,不让导出的数据会挤在一行 #下面是返回的测试数据 3 吴彦祖 32 5 王力宏 32 6 ab 32 7 黄晓明 33 8 anonymous 32
插入数据
#先看看要导入的数据格式,三列,分别是id,名字,年龄(数据是随便捏造的),放入data.user.txt 12 tf 23 13 米勒 24 14 西安电子科技大学 90 15 西安交大 90 16 北京大学 90 #OLF_IFS=$IFS #IFS="," #临时设置默认分隔符为逗号 cat data.user.txt | while read id name age do sql="insert into test.user(id, name, age) values(${id}, '${name}', ${age});" $MYSQL -e "$sql" done
输出结果
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | tf | 23 | | 13 | 米勒 | 24 | | 14 | 西安电子科技大学 | 90 | | 15 | 西安交大 | 90 | | 16 | 北京大学 | 90 | +----+--------------------------+-----+
更新数据
#先看看更新数据的格式,将左边一列替换为右边一列,只有左边一列的删除,下面数据放入update.user.txt tf twoFile 西安电子科技大学 西军电 西安交大 西安交通大学 北京大学 cat update.user.txt | while read src dst do if [ ! -z "${src}" -a ! -z "${dst}" ] then sql="update test.user set name='${dst}' where name='${src}'" fi if [ ! -z "${src}" -a -z "${dst}" ] then sql="delete from test.user where name='${src}'" fi $MYSQL -e "$sql" done
输出结果:
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | twoFile | 23 | | 13 | 米勒 | 24 | | 14 | 西军电 | 90 | | 15 | 西安交通大学 | 90 | +----+--------------------------+-----+
相关文章推荐
- shell脚本,处理mysql表格
- 使用Linux的Shell脚本定时处理MySQL超时
- shell处理mysql增、删、改、查
- mysql下的慢查询堵塞处理shell脚本
- shell简单处理mysql查询结果
- shell mysql 处理数据小结
- shell简单处理mysql查询结果的方法
- 使用Linux的Shell脚本定时处理MySQL超时
- shell并发处理mysql数据统计备份删除释放
- shell处理mysql增、删、改、查
- oracle 和MySQL 查询的时候日期的一些处理方法
- shell 调用mysql 存储过程判断真假
- unix/linux 中的SHELL 参数多于9个的处理方法
- 【未完】Gearman分布式处理,mysql队列详解
- asp.netx写入Mysql乱码的处理
- MySQL 事务处理的理解
- 数据库事务 MYSQL的事务处理功能
- java处理mysql中的事务及SavePoint的用法
- Shell如何处理ip校验
- 对于mysql_connect语法版本过低报错的处理