我是python的新手,并尝试编写一个脚本来比较来自两个数据库的数据。
特别是,尝试生成输出以列出ecah客户端的匹配/不匹配序列。
有两个数据库
AORCL数据库
SQL> select * from ffduser.client_mapping;
CLIENTNO CLIENTSEQ STATUS
---------- ---------- ----------
1 1000 VALID
2 2000 VALID
BORCL数据库
SQL> select * from ffduser.client_mapping;
CLIENTNO CLIENTSEQ STATUS
---------- ---------- ----------
1 1000 VALID
2 2002 VALID
预期输出
Clientno 1 has Clientseq 1000 in AORCL and 1000 in BORCL -> Match
Clientno 2 has Clientseq 2000 in AORCL and 2001 in BORCL -> UnMatch
==========
我写了下面的代码,但无法生成预期的输出。 我认为它可能需要嵌套循环,但我是新手。 非常感谢任何帮助。
$ cat test.py
#!/usr/bin/pytho
import cx_Oracle
pdb_name = 'AORCL'
ddb_name = 'BORCL'
pserver_name = 'ff1db03'
dserver_name = 'ff1db03'
pcon = cx_Oracle.connect('system/xxxxx@'+pserver_name+':1521/'+pdb_name)
dcon = cx_Oracle.connect('system/xxxxx@'+dserver_name+':1521/'+ddb_name)
pcur = pcon.cursor()
dcur = dcon.cursor()
pstat = pcur.execute('select clientno,clientseq from ffduser.client_mapping order by clientno').fetchall()
for plogresult in pstat:
print (pdb_name +'->'+ ' Client# '+str(plogresult[0])+' Seq No# ' +str(plogresult[1]))
dstat = dcur.execute("select clientno,clientseq from ffduser.client_mapping where status='VALID' order by clientno").fetchall()
for dlogresult in dstat:
print (pdb_name +'->'+' Client# '+str(dlogresult[0])+' Seq No# ' +str(dlogresult[1]))
pcur.close()
pcon.close()
dcur.close()
dcon.close()
$ python test.py
AORCL-> Client# 1 Seq No# 1000
AORCL-> Client# 2 Seq No# 2000
AORCL-> Client# 1 Seq No# 1000
AORCL-> Client# 2 Seq No# 2002
答案 0 :(得分:1)
我认为您需要一种我称之为select_to_name_value_mapping(table_name)
此方法返回带有"名称"的字典。作为键和Eno作为值。
mapping1=select_to_name_value_mapping('table1')
mapping2=select_to_name_value_mapping('table2')
for key1, value1 in mapping1.items():
value2=mapping2.get(key1)
print('key=%s table1=%s table2=%s' % (key1, value1, value2))
print('missing in mapping1: %s' % set(mapping1.keys())-set(mapping2.keys()))
select_to_name_value_mapping(table_name)
的实施取决于您: - )
以上是Python中的实现。人脑更容易找到这种迭代方法。您可以使用SQL获得相同的结果,但是更难以在集合中进行思考"解。我的建议:学会思考。