【发布时间】:2019-04-13 01:20:19
【问题描述】:
我有一个 CSV 文件,其中包含这些表的表名和主键,格式如下:
|表名 |主键 | |表 1 | Col1 | |表 1 | Col2 | |表 1 | Col3 | |表 2 | Col11 | |表 2 | Col12 |我想运行一个 sql 查询来验证每个表的 PK 约束。执行此操作的查询如下所示:
select Col1, Col2, Col3 from Table1
group by Col1, Col2, Col3
having count(*)>1
但我在这个文件中有数千个表。我将如何动态编写和执行此查询并将结果写入平面文件? 我想使用 Python 3 执行此操作。
尝试:
CSV:
我的 PKTest.py
def getColumns(filename):
tables = {}
with open(filename) as f:
for line in f:
line = line.strip()
if 'Primary Key' in line:
continue
cols = line.split('|')
table = cols[1].strip()
col = cols[2].strip()
if table in tables:
tables[table].append(col)
else:
tables[table] = [col]
return tables
def runSQL(table, columns):
statement = 'select {0} from {1} group by {0} having count(*) > 1'.format(', '.join(columns), table.replace(' ',''))
return statement
if __name__ == '__main__':
tables = getColumuns('PKTest.csv')
try:
#cursor to connect
for table in tables:
sql = runSQL(table,tables[table])
print(sql)
cursor.execute(sql)
for result in cursor:
print(result)
finally:
cursor.close()
ctx.close()
【问题讨论】:
标签: python sql python-3.x oracle