欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能

 更新時(shí)間:2021年02月25日 16:12:29   作者:flyingant9  
這篇文章主要介紹了python實(shí)現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

功能描述

數(shù)據(jù)庫間數(shù)據(jù)同步方式很多,在上篇博文中有總結(jié)。本文是用py程序?qū)崿F(xiàn)數(shù)據(jù)同步。
A數(shù)據(jù)庫中有幾十張表,要匯聚到B數(shù)據(jù)庫中,且表結(jié)構(gòu)一致,需要準(zhǔn)實(shí)時(shí)的進(jìn)行數(shù)據(jù)同步,用工具實(shí)現(xiàn)時(shí)對其控制有限且配置較繁瑣,故自寫程序,可自由設(shè)置同步區(qū)間,記錄自己想要的日志

代碼

本代碼實(shí)現(xiàn)功能簡單,采用面向過程,有需求的同學(xué)可以自己優(yōu)化成面向?qū)ο蠓绞?,在日志這塊缺少數(shù)據(jù)監(jiān)控,可根據(jù)需求增加。主要注意點(diǎn):
1、數(shù)據(jù)抽取時(shí)采用區(qū)間抽?。ò磿r(shí)間區(qū)間)、流式游標(biāo)迭代器+fetchone,避免內(nèi)存消耗
2、在數(shù)據(jù)插入時(shí)采用executemany(list),加快插入效率

import pymysql
import os
import datetime,time

def update_time(content):
  with open(filepathtime, 'w') as f:
    f.writelines(content)

def recode_log(content):
  with open(filepathlog, 'a') as f:
    f.writelines(content)

def transferdata():
  #1、獲取需要抽取的表,抽取數(shù)據(jù)的時(shí)間點(diǎn)
  with open(filepathtime, 'r') as f:
    lines = f.readlines() # 讀取所有數(shù)據(jù)
    print("需要同步的表信息",lines)
    for line in lines:
      startdatetime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
      tablename_list =line.split(',')
      #print(tablename_list)
      #print(tablename_list[-1])
      tablename_list[-1] = tablename_list[-1].replace('\n','')
      #print(tablename_list)
      tablename = tablename_list[0]
      updatetime = tablename_list[1]
      #print(tablename,updatetime)

      #2、抽取此表此時(shí)間點(diǎn)的數(shù)據(jù),同步
      updatetime_s = datetime.datetime.strptime(updatetime, '%Y-%m-%d %H:%M:%S')
      updatetime_e = (updatetime_s + datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
      #print(updatetime_s)
      #print(q_sql)
      db = pymysql.connect(host=host_o, port=port_o, user=user_o, passwd=passwd_o, db=db_o)
      cursor = db.cursor()
      q_sql = "select a,b,c from %s where c >= '%s' " % \
          (tablename, updatetime_s)
      #2.1 首先判斷下原表中是否有待同步數(shù)據(jù),若有則同步且更新同步的時(shí)間參考點(diǎn),若沒有則不同步且不更新同步的時(shí)間參考點(diǎn)
      try:
        cursor.execute(q_sql)
        results = cursor.fetchone()
        #print(results) #返回是元組
        #print("查詢原表數(shù)據(jù)成功!",tablename)
      except BaseException as e:
        print("查詢原表數(shù)據(jù)失?。?,tablename, str(e))
        #記錄異常日志
        updatetime_n = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        eachline_log = updatetime_n + '[erro]:' + tablename + str(e) + '\n'
        content_log.append(eachline_log)
        recode_log(content_log)
      db.close()

      if results:
        print("===============================================================================")
        print("有數(shù)據(jù)可同步",tablename)
        db = pymysql.connect(host=host_o, port=port_o, user=user_o, passwd=passwd_o, db=db_o, charset='utf8', cursorclass=pymysql.cursors.SSDictCursor)
        cursor = db.cursor()
        q_sql1 = "select a,b,c from %s where c >= '%s' and c < '%s' " % \
             (tablename, updatetime_s, updatetime_e)
        #print(q_sql1)
        result_list = []
        try:
          # startdatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
          cursor.execute(q_sql1)
          #results = cursor.fetchall()
          # enddatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
          # print(results) #返回是元組
          #使用流式游標(biāo)迭代器+fetchone,減少內(nèi)存消耗
          while True:
            result = cursor.fetchone()
            if not result:
              print("此區(qū)間無數(shù)據(jù)", q_sql1)
              break
            else:
              one_list = list(result.values())
              # print(result_list)
              result_list.append(one_list)
          print(result_list) #返回是列表
          #print("查詢數(shù)據(jù)成功!", tablename)
        except BaseException as e:
          print("查詢數(shù)據(jù)失敗!", tablename, str(e))
          # 記錄異常日志
          updatetime_n = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
          eachline_log = updatetime_n + '[erro]:' + tablename + str(e) + '\n'
          content_log.append(eachline_log)
          recode_log(content_log)
        db.close()

        results_len = (len(result_list))
        if results_len>0:
          #3、將數(shù)據(jù)插入到目標(biāo)表中,利用list提高插入效率
          i_sql = "insert into table_t(a,b,c) values (%s,%s,%s)"
          #print(i_sql)
          db = pymysql.connect(host=host_d, port=port_d, user=user_d, passwd=passwd_d, db=db_d)
          cursor = db.cursor()
          try:
            #startdatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            cursor.executemany(i_sql, result_list)
            db.commit()
            #enddatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print("插入成功!",tablename)
          except BaseException as e:
            db.rollback()
            print("插入失??!", tablename,str(e))
            #記錄異常日志
            updatetime_n = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            eachline_log = updatetime_n + '[erro]:' + tablename + str(e) + '\n'
            content_log.append(eachline_log)
            recode_log(content_log)
          db.close()
        enddatetime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

        #4、如果有數(shù)據(jù)同步,則更新參考點(diǎn)時(shí)間為下一個(gè)節(jié)點(diǎn)時(shí)間
        eachline_time = tablename+','+updatetime_e+'\n' #此時(shí)間點(diǎn)是下一個(gè)時(shí)間點(diǎn)updatetime_e
        content_time.append(eachline_time)
        print("更新表時(shí)間點(diǎn)",content_time)

        # 5、記錄成功日志
        eachline_log = enddatetime + '[success]:' + tablename + '開始時(shí)間' + startdatetime + \
          '結(jié)束時(shí)間' + enddatetime + ',同步數(shù)據(jù)量'+str(results_len)+',當(dāng)前參考點(diǎn)' + updatetime_e + '\n'
        content_log.append(eachline_log)
        print("日志信息",content_log)
        #print("===============================================================================")
      else:
        print("===============================================================================")
        print("無數(shù)據(jù)可同步",tablename)
        #db.close()
        enddatetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        # 4、如果無數(shù)據(jù)同步,則參考點(diǎn)時(shí)間不更新
        eachline_time = tablename + ',' + updatetime + '\n' #此時(shí)間點(diǎn)還是原時(shí)間updatetime
        content_time.append(eachline_time)
        print("不更新表時(shí)間點(diǎn)",content_time)

        # 5、成功日志信息
        eachline_log = enddatetime + '[success]:' + tablename + '開始時(shí)間' + startdatetime + \
          '結(jié)束時(shí)間' + enddatetime + ',同步數(shù)據(jù)量0'+ ',當(dāng)前參考點(diǎn)' + updatetime_e + '\n'
        content_log.append(eachline_log)
        print("日志信息",content_log)
        #print("===============================================================================")

    #更新配置文件,記錄日志
    update_time(content_time)
    recode_log(content_log)

if __name__ == '__main__':
  filepathtime = 'D:/test/table-time.txt'
  filepathlog = 'D:/test/table-log.txt'
  host_o = 'localhost'
  port_o = 3306
  user_o = 'root'
  passwd_o = 'root@123'
  db_o = 'csdn'
  host_d = 'localhost'
  port_d = 3306
  user_d = 'root'
  passwd_d = 'root@123'
  db_d = 'csdn'
  content_time = []
  content_log = []
  transferdata()

  #每5分鐘執(zhí)行一次同步
  # while True:
  #   transferdata()
  #   time.sleep(300)

table-time.txt配置文件,格式說明:
每行包括源庫表名、此表的最小時(shí)間time,以逗號分隔
若多個(gè)表,可配置多個(gè)時(shí)間
每次腳本執(zhí)行后,同步更新時(shí)間time。時(shí)間間隔設(shè)置為1小時(shí),可根據(jù)情況在updatetime_e中對增量進(jìn)行修改

table-log.txt
記錄每次同步任務(wù)執(zhí)行的結(jié)果,或執(zhí)行中發(fā)生異常的日志
此文件需要定期進(jìn)行清理

到此這篇關(guān)于python實(shí)現(xiàn)不同數(shù)據(jù)庫間數(shù)據(jù)同步功能的文章就介紹到這了,更多相關(guān)python實(shí)現(xiàn)數(shù)據(jù)同步內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用jupyter notebook直接打開.md格式的文件

    使用jupyter notebook直接打開.md格式的文件

    這篇文章主要介紹了使用jupyter notebook直接打開.md格式的文件,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python端口掃描簡單程序

    Python端口掃描簡單程序

    這篇文章主要為大家詳細(xì)介紹了Python端口掃描簡單程序的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • python?如何實(shí)現(xiàn)跳過異常繼續(xù)執(zhí)行

    python?如何實(shí)現(xiàn)跳過異常繼續(xù)執(zhí)行

    這篇文章主要介紹了python?如何實(shí)現(xiàn)跳過異常繼續(xù)執(zhí)行,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • scrapy框架ItemPipeline的使用

    scrapy框架ItemPipeline的使用

    本文主要介紹了scrapy框架ItemPipeline的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • 5個(gè)Python殺手級的自動化腳本分享

    5個(gè)Python殺手級的自動化腳本分享

    Python是一種功能強(qiáng)大的語言,廣泛用于自動執(zhí)行各種任務(wù),只要想通過自動化日常任務(wù)來節(jié)省時(shí)間的人,Python?都能滿足您的需求。本文整理了5個(gè)Python腳本,希望對大家有所幫助
    2023-01-01
  • Python 確定多項(xiàng)式擬合/回歸的階數(shù)實(shí)例

    Python 確定多項(xiàng)式擬合/回歸的階數(shù)實(shí)例

    今天小編就為大家分享一篇Python 確定多項(xiàng)式擬合/回歸的階數(shù)實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python實(shí)現(xiàn)批量合并Excel文件的第二張合并Excel

    Python實(shí)現(xiàn)批量合并Excel文件的第二張合并Excel

    在數(shù)據(jù)處理和分析中,經(jīng)常需要對多個(gè)Excel文件進(jìn)行批量操作,特別是當(dāng)這些文件具有相似的結(jié)構(gòu)時(shí),下面我們就來看看Python如何實(shí)現(xiàn)批量合并文件夾下所有Excel文件的第二張表吧
    2024-03-03
  • 基于Tensorflow一維卷積用法詳解

    基于Tensorflow一維卷積用法詳解

    這篇文章主要介紹了基于Tensorflow一維卷積用法詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • 淺析python 字典嵌套

    淺析python 字典嵌套

    這篇文章主要介紹了python 字典嵌套的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-09-09
  • opencv中cv2.minAreaRect函數(shù)輸出角度問題詳解

    opencv中cv2.minAreaRect函數(shù)輸出角度問題詳解

    minAreaRect返回的數(shù)據(jù)包括了矩形的中心點(diǎn),寬、高,和旋轉(zhuǎn)角度,下面這篇文章主要給大家介紹了關(guān)于opencv中cv2.minAreaRect函數(shù)輸出角度問題的相關(guān)資料,需要的朋友可以參考下
    2022-11-11

最新評論