【问题标题】:Difference Between Source and Target DB using Python使用 Python 的源数据库和目标数据库之间的区别
【发布时间】:2019-09-18 19:09:13
【问题描述】:

我正在尝试使用 Python 3、Oracle(源)从两个数据库中获取行数,并将其与 Snowflake(目标)进行比较,以检查 ETL 中是否存在任何差异。我需要将两者的结果和它们之间的差异写入一个文件。

这是我到现在为止的:

import cx_Oracle
import snowflake.connector
import sys
import csv
import os

exp_dir = os.path.normpath('C:/Users/user/Documents/')
exp_file_name = 'Count_Dff.csv'
exp_path = os.path.join(exp_dir, exp_file_name)

def runSQL(table):
    statement = "select '{0}', count(0) from  {0}".format(table.replace(' ',''))
    return statement


if __name__ == '__main__':
    """
    This function calls above functions and connects to Snowflake
    """
    tables = ['Table_1','Table_2']
    my_list = []
    try:
        conn_str = u'user/paswword@host/service'
        curcon = cx_Oracle.connect(conn_str) 
        cursor = curcon.cursor()

        ctx = snowflake.connector.connect(user='****', password='****', account='****', role='***')
        cursor2 = ctx.cursor()
        cursor2.execute("USE WAREHOUSE ****")
        cursor2.execute("USE DATABASE ****")
        cursor2.execute("USE SCHEMA ****")

        for table in tables:
            my_dict = {}
            sql = runSQL(table)
            cursor.execute(sql)
            my_list.append(cursor)

        outputFile = open(exp_path,'w') # 'wb'
        output = csv.writer(outputFile)
        for data in my_list:
            output.writerow(data)


    finally:
        cursor.close()
        cursor2.close()


显然这不是一个完整的解决方案。我对下一步有点迷失了。有什么意见吗?

预期输出:

|表名 |来源计数 |目标计数 |差异 | |表1 | 14 | 12 | 2 |

【问题讨论】:

    标签: python sql python-3.x oracle snowflake-cloud-data-platform


    【解决方案1】:

    您没有针对 Snowflake 数据库运行 SQL 命令。您可能应该这样做:

    for table in tables:
        sql = runSQL(table)
        cursor.execute(sql)
        o_count = cursor.fetchone()[1]
        cursor2.execute(sql)
        s_count = cursor2.fetchone()[1]
        my_list.append([table, o_count, s_count, o_count - s_count])
    

    编辑 增加了对评论的回应。

    【讨论】:

    • 是的。我没有写完它,因为我不确定如何在同一行上为同一个表编写两个游标的结果。你有什么想法吗?
    • 在您的问题中添加所需输出的描述。我的答案中的代码 sn-p 会将两个光标的计数放在输出的同一行上。目前尚不清楚您还在寻找什么。
    • 您的代码有效。我遇到的问题是它写入重复的行。我已经用预期的输出编辑了我的问题。我还需要源和目标之间的区别
    • 如果您的表列表(tables)是唯一的,您如何在输出中获得重复行?要获取行数的差异,只需从返回的值中计算出来,就像在编辑的答案中一样。
    • 使用您最初发布的代码,只需在处理表格之前执行output.writerow(['TABLE','SOURCE','TARGET','DIFFERENCE'])
    猜你喜欢
    • 2011-04-11
    • 2010-12-24
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多