簡體   English   中英

使用 Python 將數據從 MSSQL 數據庫復制到 Postgresql 數據庫

[英]copy data from MSSQL database to Postgresql database with Python

我有兩個 2 數據庫。 一個使用 MSSQL,另一個使用 Postgresql。 我希望我的 python 腳本每天都在運行(為此我在 linux 上使用 cron-job)。 MSSQL 數據庫中的數據應復制到 Postgresql 數據庫中。 我有一個想法,但它不起作用。 你可以幫幫我嗎??? 也許我的解決方案是完全錯誤的......

那是我的代碼:

import pymssql, psycopg2

class DatabaseRequest:

    def __init__(self):
        self.conn1 = pymssql.connect(host='****', user='****', password='****', database='****')
        self.conn2 = psycopg2.connect("dbname='****' user='****' host='*****' password='****'")

        self.cur1 = self.conn1.cursor()
        self.cur2 = self.conn2.cursor()

    def request_proc(self, rows):
        self.cur1.execute("SELECT top 10  tag, site, plant, unit, line, ProcessID AS pid, Count(ReadTime) AS mods \
                        FROM ( \
                        select dateadd(dd, -1, convert(varchar, getDate(),111)) \
                        as tag, ReadTime, processID, subid, PR.Site, PR.Plant, PR.Unit, PR.Line \
                        from FactBarcodeReading BCR with(nolock) \
                        inner join DimProcess PR on BCR.ProcessKey = PR.ProcessKey \
                        where PR.ProcessID IN  (802, 1190, 1800, 3090, 3590, 4390, 4590, 4800, 5000, 5400, 4190) \
                        and ReadTime between dateadd(dd, -1, convert(varchar, getDate(),111)) and dateadd(dd, -0, convert(varchar, getDate(),111)) \
                        ) a \
                        GROUP BY tag, site, plant, unit, line, ProcessID \
                        ORDER BY site, plant, unit, line, ProcessID")

        rows = self.cur1.fetchone()

       # return rows   


    def insert_proc(self):
        self.cur2.execute("INSERT INTO 20091229global (proddate, site, plant, unit, line, pid, mods) \
                        VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"
                        % self.cur1.fetchone())


        a = DatabaseRequest()
        print a.insert_proc()

PS:request_proc 工作正常。

如果代碼沒有產生錯誤,但插入的記錄沒有出現在 Postgresql 數據庫中,您很可能需要在執行 INSERT 語句后添加self.conn2.commit() 這會將每個事務提交到數據庫。

根據文檔,還可以啟用自動交易。

您還需要將 cursor (cur1) 傳遞到 insert_proc -->

def insert_proc(self, cur1):
  self.cur2.execute("INSERT INTO 20091229global (proddate, site, plant, unit, line, pid, mods) \
                        VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"
                        % self.cur1.fetchone())

在嘗試自己找到答案后才看到這個帖子。 您可以使用 psycopg2.extras 中稱為 execute_values() 的方法。

在文檔https://www.psycopg.org/docs/extras.html中,您可以在底部附近找到它。 只需傳遞一個字符串變量,然后將該占位符定義為值列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM