最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

功能描述

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

代碼

本代碼實(shí)現(xiàn)功能簡單,采用面向過程,有需求的同學(xué)可以自己優(yōu)化成面向?qū)ο蠓绞?,在日志這塊缺少數(shù)據(jù)監(jiān)控,可根據(jù)需求增加。主要注意點(diǎn):
1、數(shù)據(jù)抽取時采用區(qū)間抽取(按時間區(qū)間)、流式游標(biāo)迭代器+fetchone,避免內(nèi)存消耗
2、在數(shù)據(jù)插入時采用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ù)的時間點(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、抽取此表此時間點(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ù),若有則同步且更新同步的時間參考點(diǎn),若沒有則不同步且不更新同步的時間參考點(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)時間為下一個節(jié)點(diǎn)時間
        eachline_time = tablename+','+updatetime_e+'\n' #此時間點(diǎn)是下一個時間點(diǎn)updatetime_e
        content_time.append(eachline_time)
        print("更新表時間點(diǎn)",content_time)

        # 5、記錄成功日志
        eachline_log = enddatetime + '[success]:' + tablename + '開始時間' + startdatetime + \
          '結(jié)束時間' + 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)時間不更新
        eachline_time = tablename + ',' + updatetime + '\n' #此時間點(diǎn)還是原時間updatetime
        content_time.append(eachline_time)
        print("不更新表時間點(diǎn)",content_time)

        # 5、成功日志信息
        eachline_log = enddatetime + '[success]:' + tablename + '開始時間' + startdatetime + \
          '結(jié)束時間' + 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配置文件,格式說明:
每行包括源庫表名、此表的最小時間time,以逗號分隔
若多個表,可配置多個時間
每次腳本執(zhí)行后,同步更新時間time。時間間隔設(shè)置為1小時,可根據(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)文章

  • Django分頁查詢并返回jsons數(shù)據(jù)(中文亂碼解決方法)

    Django分頁查詢并返回jsons數(shù)據(jù)(中文亂碼解決方法)

    這篇文章主要介紹了Django分頁查詢并返回jsons數(shù)據(jù)(中文亂碼解決方法),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • Django如何批量創(chuàng)建Model

    Django如何批量創(chuàng)建Model

    將測試數(shù)據(jù)全部敲入數(shù)據(jù)庫非常繁瑣,這篇文章主要介紹了Django如何批量創(chuàng)建Model,幫助大家快速錄入數(shù)據(jù),感興趣的朋友可以了解下
    2020-09-09
  • Python DBM模塊輕松使用小型數(shù)據(jù)庫存儲管理數(shù)據(jù)

    Python DBM模塊輕松使用小型數(shù)據(jù)庫存儲管理數(shù)據(jù)

    這篇文章主要介紹了Python DBM模塊輕松使用小型數(shù)據(jù)庫存儲管理數(shù)據(jù),它可以讓你輕松地存儲和管理鍵值對數(shù)據(jù),可以使用 dbm 模塊來操作 DBM 文件,或者使用 shelve 模塊來存儲任意類型的 Python 對象
    2024-01-01
  • 如何在Python中對文件進(jìn)行操作

    如何在Python中對文件進(jìn)行操作

    這篇文章主要介紹了如何在Python中對文件進(jìn)行操作,文章圍繞主題展開內(nèi)容,即使用Python中內(nèi)置的open()函數(shù)來打開文件,返回文件對象,并對文件進(jìn)行處理
    2022-08-08
  • Python3中urlencode和urldecode的用法詳解

    Python3中urlencode和urldecode的用法詳解

    今天小編就為大家分享一篇Python3中urlencode和urldecode的用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python中順序表原理與實(shí)現(xiàn)方法詳解

    Python中順序表原理與實(shí)現(xiàn)方法詳解

    這篇文章主要介紹了Python中順序表原理與實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python順序表的概念、原理及增刪查等相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2019-12-12
  • 教你python 中如何取出colomap部分的顏色范圍

    教你python 中如何取出colomap部分的顏色范圍

    這篇文章主要介紹了python 中如何取出colomap部分的顏色范圍,本文以以jet為例給大家提供一種方法,可以提取colormap色標(biāo)中的一部分,取出我們滿意的色標(biāo)區(qū)域,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • 詳解如何利用Python繪制迷宮小游戲

    詳解如何利用Python繪制迷宮小游戲

    這篇文章主要為大家介紹了如何用Python制作一個迷宮游戲,文中的示例代碼講解詳細(xì),對大家更好的理解和學(xué)習(xí)python有一定幫助,感興趣的朋友可以了解下
    2022-02-02
  • Python批量修改文件名案例匯總

    Python批量修改文件名案例匯總

    在文件管理和數(shù)據(jù)處理中,批量修改文件名是一項(xiàng)常見且重要的任務(wù),Python作為一種功能強(qiáng)大的編程語言,提供了豐富的庫和工具來簡化這一過程,本文將結(jié)合實(shí)際案例,詳細(xì)介紹如何通過Python批量修改文件名,需要的朋友可以參考下
    2024-08-08
  • Pyhton自動化測試持續(xù)集成和Jenkins

    Pyhton自動化測試持續(xù)集成和Jenkins

    這篇文章介紹了Pyhton自動化測試持續(xù)集成和Jenkins,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07

最新評論

赣州市| 偏关县| 镶黄旗| 兴国县| 嘉祥县| 磴口县| 巴青县| 耒阳市| 永康市| 焉耆| 东港市| 福海县| 五华县| 鄂托克前旗| 新干县| 腾冲县| 桐柏县| 开远市| 汝阳县| 新密市| 商水县| 从化市| 浏阳市| 邻水| 临潭县| 太仆寺旗| 望江县| 泸定县| 蒲城县| 咸阳市| 霍林郭勒市| 邮箱| 鸡东县| 互助| 怀集县| 虹口区| 北辰区| 富源县| 射阳县| 文安县| 南澳县|