Shell进行MySQL表跨服务器增量更新同步小脚本

来源:互联网 发布:js中json数组 编辑:程序博客网 时间:2024/06/05 22:44


     工作所需写的小脚本。

# !/bin/bash  # Author    : 蛙鳜鸡鹳狸猿# create_ts : 2017年 01月 03日 星期二 14:48:14 CST# program   : Incremental transfer table records between MySQL servers# crontab   : 11/min#  #  # __init__  host_src=yourht_A    # source db server config listuser_src=rootpswd_src=123dbas_src=yourdb_A#host_tar=yourht_B    # target db server config listuser_tar=rootpswd_tar=456dbas_tar=yourdb_B#cach_dump=/    # cache directory config# # # define execute sql functionfunction sqlrun_src(){mysql -h${host_src} -u${user_src} -p${pswd_src} <<EOF$1EOF}function sqlrun_tar(){mysql -h${host_tar} -u${user_tar} -p${pswd_tar} <<EOF$1EOF}#  #  # do synchronizetar_run="SELECT MAX(id) AS id FROM ${dbas_tar}.syn_tab;"if id_ori=$(sqlrun_tar "${tar_run}") && id=${id_ori#id}then echo -e "\n\n …………Get Max id ${id}………… \n\n"else exit && echo -e "\n\n …………Get Max id Failed………… \n\n"fi# src_run="SELECT * FROM ${dbas_src}.syn_tab WHERE id > ${id};"if sqlrun_src "${src_run}" > ${cach_dump}syn_tab.txtthen echo -e "\n\n …………Write syn_tab data OK………… \n\n"else exit && echo -e "\n\n …………Write syn_tab data Failed………… \n\n"fi# if sed -i '1, $s/NULL/\\N/g' ${cach_dump}syn_tab.txt && /opt/mysql/bin/mysqlimport -h${host_tar} -u${user_tar} -p${pswd_tar} --ignore-lines=1 --local ${dbas_tar} ${cach_dump}syn_tab.txtthen echo -e "\n\n …………Import syn_tab data OK………… \n\n"else exit && echo -e "\n\n …………Write syn_tab data Failed………… \n\n"fi# #   # clear cache  ifcd ${cach_dump} && rm -f syn_tab.txtthen echo -e "\n\n ……\(^o^)/ GangBaDei \(^o^)/…… \n\n"else exit && echo -e "\n\n ……o(>﹏<)o YaMieDie o(>﹏<)o…… \n\n"fi# # 

     如脚本所示,要实现增量更新同步,首先,得确保两台MySQL服务器的表中有一个可以作为标识增长的字段,我的脚本中用的是自增长的主键(id),这样效率最高性能最好。然后从目标库中获取同步点(MAX(id)),接着去源库获取同步数据写入文本文件,最后借用mysqlimport工具将数据导入目标库对应表中,OK了。


     需要注意的是,缓存的文本文件名(第一个逗点以前部分)要与mysqlimport进的数据库表名一致。写入时需要忽略文件中第一行的表字段名(通过--ignore-lines=1)。最后,文件中的NULL值要在import之前替换成换行符“\n”,主要目的是避免日期时间戳字段中的NULL值导入失真,具体参考http://blog.csdn.net/sweeper_freedoman/article/details/54586482。



0 0
原创粉丝点击