您的位置:首页 > 运维架构 > Shell

使用Shell进行Mysql间数据以文本形式传输及注意事项

2016-12-07 20:54 549 查看
1、程序目录结构


[root@master timeline]# pwd
/root/timeline
[root@master timeline]# tree
.
├── data
│   ├── jellyfish_user.user_profile.dat
│   └── jellyfish_user.user_profile.list
└── etl_script
└── user_profile.sh

2 directories, 3 files


2、进行Mysql数据卸装Shell程序

[root@master etl_script]# cat user_profile.sh 


#!/bin/bash

rm -rf /root/timeline/data/jellyfish_user.user_profile.dat

/usr/bin/mysql -hsrc-ip -Psrc-port -usrc-user -psrc-passwd -N -e"select table_name from information_schema.tables where table_schema='jellyfish_user' and table_name like 'user_profile%';" > /root/timeline/data/jellyfish_user.user_profile.list

i=1

for tab in $(cat /root/timeline/data/jellyfish_user.user_profile.list)
do

col_num=$i
tab_name=$(awk -F "|" 'NR=='$col_num' {print $1}'  /root/timeline/data/jellyfish_user.user_profile.list)
echo $tab_name

#user_profile data proc ...
/usr/bin/mysql -hsrc-ip -Psrc-port -usrc-user -psrc-passwd -N -e"set character_set_results=utf8;select CONCAT(ifnull(\`uid\`,''),'|',ifnull(\`nickname\`,''),'|',ifnull(\`avatar\`,''),'|',ifnull(\`signature\`,''),'|',ifnull(\`gender\`,''),'|',ifnull(\`type\`,''),'|',ifnull(\`source\`,''),'|',ifnull(\`phone_num_verified\`,''),'|',ifnull(\`id_card_verified\`,''),'|',ifnull(\`state\`,''),'|',ifnull(\`last_login_time\`,''),'|',ifnull(\`created_time\`,''),'|',ifnull(\`updated_time\`,'')) from jellyfish_user.$tab_name;" >> /root/timeline/data/jellyfish_user.user_profile.dat

: $(( i++ ))
done

/usr/bin/mysql -htgt-ip -utgt-user -ptgt-passwd -e "set character_set_results=utf8;use timeline;truncate table user_profile;load data local infile '/root/timeline/data/jellyfish_user.user_profile.dat' into table user_profile character set utf8 fields terminated by '|' enclosed by '' lines terminated by '\n' ignore 0 lines;"


3、说明及注意事项
3.1、关于中文乱码问题
导出时出现乱码,需要在命令行前添加【set character_set_results=utf8;】;导入时出现乱码,需要添加load data选项【character set utf8】放在into table与fileds中间。

3.2、Mysql分表的导出
导出Mysql分表,采用如例所示的到Mysql字典中查找的方法,循环逐个导出追加数据文件的方式。

3.3、源表字段格式的查找
源表字段列部分采用通过Sql进行拼脚本的方式,但要注意,需要手动去除所得结果的【,'|'】,但最后的括号不去除
-- 取源表字段的SQL:
select CONCAT('CONCAT(',GROUP_CONCAT(concat('ifnull(\\`',b.COLUMN_NAME,'\\`,\'\')',',\'|\'')),')')
from information_schema.`TABLES` a
left join information_schema.`COLUMNS` b on a.TABLE_NAME=b.TABLE_NAME and a.TABLE_SCHEMA=b.TABLE_SCHEMA
where a.table_NAME='time_line';

结果示例:
CONCAT(ifnull(\`id\`,''),'|',ifnull(\`uid\`,''),'|',ifnull(\`type\`,''),'|',ifnull(\`target_key\`,''),'|',ifnull(\`state\`,''),'|',ifnull(\`created_time\`,''),'|',ifnull(\`updated_time\`,''),'|')

3.4、表结构说明
例子中要求源、目标表结构相同;如若选取源的部分字段装载到目标表中,则可以在[3.3]的Sql中过滤对应的字段进行筛选。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: