一、目的
每天将数据库A中某些表的数据增量备份到数据库B中相应的表中
二、应用场景
做了个运维服务管理平台,其中有一部分是对公司各游戏下载次数的统计。因为部分游戏下载服务器是在外网(其余通过CDN提供下载),统计的方法是直接在游戏下载服务器上每天执行脚本分析下载日志,然后将各游戏每天的下载次数数据插入到外网的一个数据库。运维服务管理平台web服务端部署在内网。
发现问题:运维服务管理平台因为是使用外网的数据,导致访问速度比较慢
解决方案:运维服务管理平台使用内网数据库,将外网数据库中每天的游戏更新次数数据,每天增量插入到内网的数据库中。
三、具体步骤
1、编写python脚本,查询外网数据库中相应表中昨天的数据,然后插入到内网数据库中,代码如下# coding=utf-8
"""
#Author: blackholll
#Email: blackholll@163.com
#Created: 2014-04-16
#Purpose: sync increment date between two datebases
#Tables: ywreport_gameupdate,ywreport_lobbylogintimes
"""
import MySQLdb
import datetime
todaydate = datetime.datetime.now() #获取今天的日期
yesterdaydate = str((todaydate-datetime.timedelta(days=1)).date()) #获取昨天的日期
#连接数据库
try:
connfrom = MySQLdb.connect(host='1.1.1.1',user='blackholll',passwd='123456',db='dbname',port=3306,charset='utf8')
curfrom = connfrom.cursor()
connto = MySQLdb.connect(host='192.168.1.6',user='blackholll',passwd='123456',db='dbname2',port=3306,charset='utf8')
curto = connto.cursor()
#for table ywreport_gameupdate
sqls= "select *from ywreport_gameupdate where date='%s'"%yesterdaydate #查询昨天的数据
curfrom.execute("select *from ywreport_gameupdate where date='%s'"%yesterdaydate)
rows = curfrom.fetchall()
for row in rows:
print row
sqlstr = "insert into ywreport_gameupdate(id,gameid,date,plateform_id,subarea,server_id,updates,operations,uptype_id,areaid) values(%d,'%s','%s','%d','%d',%d,%d,'%s',%d,%d)"%(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9])
curto.execute(sqlstr)
#for table ywreport_lobbylogintimes
curfrom.execute("select *from ywreport_lobbylogintimes where date='%s'"%yesterdaydate) #查询昨天的数据
rows = curfrom.fetchall()
for row in rows:
sqlstr = "insert into ywreport_lobbylogintimes(id,server_id,date,lobbytype_id,logintimes) values(%d,%d,'%s',%d,%d)"%(row[0],row[1],row[2],row[3],row[4])
print sqlstr
curto.execute(sqlstr)
#关闭数据库连接
connfrom.close()
curfrom.close()
connto.close()
curto.close()
except MySQLdb.Error,e:
print e
注:本脚本实现了将1.1.1.1上数据库中ywreport_gameupdate和ywreport_lobbylogintimes表中昨天的数据插入到192.168.1.6相应的表中,
表名可以不同,字段名也可以不同,只需要稍微改下代码就行了。 另:本脚本需要安装mysqldb模块,安装方法在此不作说明,读者可以百度
2、通过linux的contab或者windows的计划任务实现每天定时执行。
略