<python新手>比较使用python从不同数据库查询的多个表的记录计数



我有两种方法来查询具有多个表的两个不同数据库,我只需要比较检索到的记录计数。有什么方法可以让我不需要先导出结果文件,然后再使用pandas进行比较?实现这个场景的最佳方法是什么?

我认为我们需要创建一个空列表,然后添加for循环来附加每个表,但是它将如何为每个表附加记录计数呢?

在下面创建一个虚拟代码:

table_list = ['tableA', 'tableB', 'tableC', 'tableD']
def database_1(conn, table_list):
list1 = []
for table in table_list:
sql = "select count(*) from tableA where date='today'"
exec = conn.cursor.execute(sql)
result = exec.fetchone()
count1 = result[0]
add = list1.append(count1)       
return list1

def database_2(conx, table_list):
list2= []
for table in table_list:
sql = "select count(*) from tableA where date='today'"
exec = conx.cursor.execute(sql)
result = exec.fetchone()
count2 = result[0]
add = list2.append(count2)
return list2
def call_both():
"compare the record counts from both for each table and log details of the comparison, not sure what to do here"
if database1(conn, table_list) = database2(conx, table_list)

我尝试创建空字典而不是列表,这样我们就可以有表和记录计数(键值对)

table_list = ['tableA', 'tableB', 'tableC', 'tableD']
def database_1(table_list):
dict1={'tableA':4, 'tableB':6,'tableC':7,'tableD':9}
list1 = {}
for table in table_list:
count1 = dict1[table]
# add = list1.append(count1)
add = list1.update({table: count1})
return list1

def database_2(table_list):
dict2 = {'tableA': 12, 'tableB': 6, 'tableC': 7, 'tableD': 9}
list2 = {}
for table in table_list:
count1 = dict2[table]
add = list2.update({table: count1})
return list2
def call_both():
"compare the record counts from both for each table and log details of the comparison, not sure what to do here"
first = database_1(table_list)
second = database_2(table_list)
print('database 1 values:'+ str(first))
print('database 2 values:' + str(second))
call_both()

输出:数据库1的值:{'tableA': 4, 'tableB': 6, 'tableC': 7, ' tableed ': 9}{'tableA': 12, 'tableB': 6, 'tableC': 7, ' tableed ': 9}

现在我需要比较两个字典

def call_both():
"compare the record counts from both for each table and log details of the comparison, not sure what to do here"
first = database_1(table_list)
second = database_2(table_list)
diff = DeepDiff(first, second, ignore_string_case=True, verbose_level=2)

输出:{"values_changed":{"根("为多")":{"old_value":"new_value":12日4},"根("tableC")":{"new_value":0,"old_value":7}}}

最新更新