Python3 實現簡單資料同步功能

2021-09-30 01:23:33 字數 1835 閱讀 1441

工作中需要將現網伺服器中的資料同步至備庫中,用python實現很簡單,具體如下

import pymysql

'''author:shikailiang

function:實現簡單etl的功能

'''# 執行的sql語句

sql=

''''''

# 定義備庫的連線

beiku_conn = pymysql.connect(host=

"", user=

"", password=

"", database=

"", charset=

"utf8"

)beiku_cursor = beiku_conn.cursor(

)# 定義現網的連線

now_conn = pymysql.connect(host=

"", user=

"", password=

"", database=

"", charset=

"utf8"

)now_cursor = now_conn.cursor(

)now_cursor.execute(sql)

from_data=now_cursor.fetchall(

)# 獲取查詢結果的長度

rowcount =

len(from_data)

# 下面語句拼接sql,實現一次插入1000條,j為行標記

j =1

sql =

""sql1 =

"insert into tb_immediately_inventory_test(create_time,物料編碼,物料名稱,庫存主單位,庫存量) values"

for i in from_data:

sql2 =((

"("+

'"{}",'*5

)[:-

1]+")").

format

(i[0

], i[1]

, i[2]

, i[3]

, i[4]

) sql2 = sql2.replace(

'"none"'

,"null"

) sql = sql +

","+ sql2

ifdivmod

(j,1000)[

1]==0

or j == rowcount:

# 如果執行錯誤回滾當前事務

try:

beiku_cursor.execute(sql1 + sql[1:

])except

: beiku_conn.rollback(

)print

(sql1 + sql[1:

])continue

sql =

"" j = j +

1# 每一百條列印

ifdivmod

(j,1000)[

1]==0

:print

("已經插入tb_immediately_inventory_test"

+str

(j)+

"條")

print

("插入"

+str

(j -1)

+"條"

)# 關閉資料庫連線

beiku_conn.commit(

)beiku_cursor.close(

)beiku_conn.close(

)now_cursor.close(

)now_conn.close(

)

Python3簡單實現氣泡排序

話不多說,直接上 coding utf 8 class bubblesort object resultstr def init self,datas self.datas datas self.datas len len datas def sort self for i in range sel...

Python3簡單實現選擇排序

coding utf 8 class selectionsort object resultstr 初始化selectionsort def init self,datas self.datas datas self.datas len len datas def sort self for i i...

簡單資料分布分析及python實現

資料離中趨勢分析 資料的分布分析 資料集中趨勢分析是為了衡量資料的集中程度,常用的集中趨勢衡量指標包括資料的平均值 中位數 眾數和分位數。平均值和中位數多作為連續資料的衡量指標,眾數多作為離散資料的衡量指標。python實現。import pandas as pd import numpy as n...