好湿?好紧?好多水好爽自慰,久久久噜久噜久久综合,成人做爰A片免费看黄冈,机机对机机30分钟无遮挡

主頁 > 知識庫 > python實現MySQL指定表增量同步數據到clickhouse的腳本

python實現MySQL指定表增量同步數據到clickhouse的腳本

熱門標簽:舉辦過冬奧會的城市地圖標注 螳螂科技外呼系統怎么用 400電話申請資格 電銷機器人系統廠家鄭州 正安縣地圖標注app 阿里電話機器人對話 地圖地圖標注有嘆號 遼寧智能外呼系統需要多少錢 qt百度地圖標注

python實現MySQL指定表增量同步數據到clickhouse,腳本如下:

#!/usr/bin/env python3
# _*_ coding:utf8 _*_
 
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (DeleteRowsEvent,UpdateRowsEvent,WriteRowsEvent,)
import clickhouse_driver
import configparser
import os
 
configfile='repl.ini'
########## 配置文件repl.ini 操作 ##################
def create_configfile(configfile,log_file,log_pos):
  config = configparser.ConfigParser()
 
  if not os.path.exists(configfile):
    config['replinfo'] = {'log_file':log_file,'log_pos':str(log_pos)}
 
    with open(configfile,'w+') as f:
      config.write(f)
 
### repl.ini 寫操作 ##################
def write_config(configfile,log_file,log_pos):
  config = configparser.ConfigParser()
  config.read(configfile)
 
  config.set('replinfo','log_file',log_file)
  config.set('replinfo','log_pos',str(log_pos))
 
  if os.path.exists(configfile):
    with open(configfile,'w+') as f:
      config.write(f)
  else:
    create_configfile(configfile)
 
### 配置文件repl.ini 讀操作 ##################
def read_config(configfile):
  config = configparser.ConfigParser()
  config.read(configfile)
  # print(config['replinfo']['log_file'])
  # print(config['replinfo']['log_pos'])
  return (config['replinfo']['log_file'],int(config['replinfo']['log_pos']))
 
############# clickhouse 操作 ##################
def ops_clickhouse(db,table,sql):
  column_type_dic={}
  try:
    client = clickhouse_driver.Client(host='127.0.0.1',\

                     port=9000,\

                     user='default',\

                     password='clickhouse')
    # sql="select name,type from system.columns where database='{0}' and table='{1}'".format(db,table)
    client.execute(sql)
 
  except Exception as error:
    message = "獲取clickhouse里面的字段類型錯誤. %s" % (error)
    # logger.error(message)
    print(message)
    exit(1)
 
MYSQL_SETTINGS = {'host':'127.0.0.1','port':13306,'user':'root','passwd':'Root@0101'}
only_events=(DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent)
def main():
  ## 每次重啟時,讀取上次同步的log_file,log_pos
  (log_file,log_pos) = read_config(configfile)
  # print(log_file+'|'+ str(log_pos))
  print('-----------------------------------------------------------------------------')
  stream = BinLogStreamReader(connection_settings=MYSQL_SETTINGS, resume_stream=True, blocking=True, \

                server_id=10,
                 only_tables='t_repl', only_schemas='test', \

                log_file=log_file,log_pos=log_pos, \

                only_events=only_events, \

                fail_on_table_metadata_unavailable=True, slave_heartbeat=10)
 
  try:
    for binlogevent in stream:
      for row in binlogevent.rows:
        ## delete操作
        if isinstance(binlogevent, DeleteRowsEvent):
          info = dict(row["values"].items())
          # print("DELETE FROM `%s`.`%s` WHERE %s = %s ;" %(binlogevent.schema ,binlogevent.table,binlogevent.primary_key,info[binlogevent.primary_key]) )
          # print("ALTER TABLE `%s`.`%s` DELETE WHERE %s = %s ;" %(binlogevent.schema ,binlogevent.table,binlogevent.primary_key,info[binlogevent.primary_key]) )
          sql="ALTER TABLE `%s`.`%s` DELETE WHERE %s = %s ;" %(binlogevent.schema ,binlogevent.table,binlogevent.primary_key,info[binlogevent.primary_key])
 
        ## update 操作
        elif isinstance(binlogevent, UpdateRowsEvent):
          info_before = dict(row["before_values"].items())
          info_after = dict(row["after_values"].items())
          # info_set = str(info_after).replace(":","=").replace("{","").replace("}","")
          info_set = str(info_after).replace(":", "=").replace("{", "").replace("}", "").replace("'","")
          # print("UPDATE `%s`.`%s` SET %s WHERE %s = %s ;"%(binlogevent.schema,binlogevent.table,info_set,binlogevent.primary_key,info_before[binlogevent.primary_key]  ) )
          # print("ALTER TABLE %s.%s UPDATE %s WHERE %s = %s ;"%(binlogevent.schema,binlogevent.table,info_set,binlogevent.primary_key,info_before[binlogevent.primary_key]  ) )
          sql = "ALTER TABLE %s.%s UPDATE %s WHERE %s = %s ;"%(binlogevent.schema,binlogevent.table,info_set,binlogevent.primary_key,info_before[binlogevent.primary_key]  )
 
        ## insert 操作
        elif isinstance(binlogevent, WriteRowsEvent):
          info = dict(row["values"].items())
          # print("INSERT INTO %s.%s(%s)VALUES%s ;"%(binlogevent.schema,binlogevent.table , ','.join(info.keys()) ,str(tuple(info.values())) ) )
          sql = "INSERT INTO %s.%s(%s)VALUES%s ;"%(binlogevent.schema,binlogevent.table , ','.join(info.keys()) ,str(tuple(info.values())) )
        ops_clickhouse('test', 't_repl',sql )
 
        # 當前log_file,log_pos寫入配置文件
        write_config(configfile, stream.log_file, stream.log_pos)
 
  except Exception as e:
    print(e)
  finally:
    stream.close()
 
if __name__ == "__main__":
  main()
 
 
 
'''
BinLogStreamReader()參數
ctl_connection_settings:集群保存模式信息的連接設置
resume_stream:從位置或binlog的最新事件或舊的可用事件開始
log_file:設置復制開始日志文件
log_pos:設置復制開始日志pos(resume_stream應該為true)
auto_position:使用master_auto_position gtid設置位置
blocking:在流上讀取被阻止
only_events:允許的事件數組
ignored_events:被忽略的事件數組
only_tables:包含要觀看的表的數組(僅適用于binlog_format ROW)
ignored_tables:包含要跳過的表的數組
only_schemas:包含要觀看的模式的數組
ignored_schemas:包含要跳過的模式的數組
freeze_schema:如果為true,則不支持ALTER TABLE。速度更快。
skip_to_timestamp:在達到指定的時間戳之前忽略所有事件。
report_slave:在SHOW SLAVE HOSTS中報告奴隸。
slave_uuid:在SHOW SLAVE HOSTS中報告slave_uuid。
fail_on_table_metadata_unavailable:如果我們無法獲取有關row_events的表信息,應該引發異常
slave_heartbeat:(秒)主站應主動發送心跳連接。這也減少了復制恢復時GTID復制的流量(在許多事件在binlog中跳過的情況下)。請參閱mysql文檔中的MASTER_HEARTBEAT_PERIOD以了解語義
'''

知識點擴展:

MySQL備份-增量同步

mysql增量同步主要使用binlog文件進行同步,binlog文件主要記錄的是數據庫更新操作相關的內容。

1. 備份數據的意義

針對不同業務,7*24小時提供服務和數據的重要性不同。
數據庫數據是比較核心的數據,對企業的經營至關重要,數據庫備份顯得尤為重要。

2. 備份數據庫

MySQL數據庫自帶的備份命令 `mysqldump`,基本使用方法:
語法:`mysqldump -u username -p password dbname > filename.sql`

執行備份命令

`mysqldump -uroot -pmysqladmin db_test > /opt/mysql_bak.sql`

查看備份內容

`grep -v "#|\*|--|^$" /opt/mysql_bak.sql`

到此這篇關于python實現MySQL指定表增量同步數據到clickhouse的腳本的文章就介紹到這了,更多相關python實現MySQL增量同步數據內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • 基于python的mysql復制工具詳解
  • 由Python編寫的MySQL管理工具代碼實例
  • python實現讀取excel寫入mysql的小工具詳解
  • Python操作MySQL數據庫的簡單步驟分享
  • Python爬蟲爬取全球疫情數據并存儲到mysql數據庫的步驟
  • Python爬取騰訊疫情實時數據并存儲到mysql數據庫的示例代碼
  • 解決python mysql insert語句的問題
  • python 在mysql中插入null空值的操作
  • 用python開發一款操作MySQL的小工具

標簽:昭通 合肥 興安盟 淘寶好評回訪 濟源 信陽 阜新 隨州

巨人網絡通訊聲明:本文標題《python實現MySQL指定表增量同步數據到clickhouse的腳本》,本文關鍵詞  python,實現,MySQL,指定,表,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《python實現MySQL指定表增量同步數據到clickhouse的腳本》相關的同類信息!
  • 本頁收集關于python實現MySQL指定表增量同步數據到clickhouse的腳本的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 56pao无码视频在线观看| 正在播放国产多p交换视频| japanesefree日本护士| 成年女人免费v片| 最近2019中文字幕在线| 厨房婬乱公妇1-42小说| 男女男精品免费视频网站| 人人干人人爱| 曰批全过程免费视频在线观看| 最近韩国高清在线| jiazzjizzjizz大学生| 国产美女在线精品亚洲二区| 国产免费人成在线视频视频| 九一视频在线免费观看 | 人妻公妇公侵HD中字| 金莎朗大尺度床戏裸乳江南男女| 日日射影院| 国产无遮挡又黄又爽又色学生软件 | 国产村偷农村妇女视频| 99热精品动漫在线观看| 爽?躁多水?快?深点快斗| 两男一女3p大尺度电影| 高清国产一区| 中文字幕乱码熟| 狂揉大乳子免费视频| 韩国三姐妹| 国产第二区| 免费无遮挡??视频在线观看| 呜不要做了gl百合扶她| 97国产精品久久碰碰蜜臀小说| 武松大战潘金莲嗯啊轻点| 扒开腿开嫩苞| 黄圣依老公| 看草逼| 国产香蕉75在线播放| 19嘘禁止想象豆瓣超清70分钟| 国产91极品福利手机观看| 被大肉榛征服的警花小说| 精品欧美一区二区三区成人片在线| 一级婬片A片AAAA毛片A级| 雷狮在安迷修的体内塞|