问题:我无法弄清楚如何以正确的方式运行查询,以便返回映射的字典。该查询将使用来自多个表的计数。
我正在使用psycopg2作为postgresql数据库,我将使用结果创建一个关于这些计数的日常增量报告。
鉴于此,有人可以提供一个关于如何执行多个查询并返回我可以用于比较目的的字典的示例吗?谢谢!在这里的某个地方需要for循环中的图像。
tables = ['table1', 'table2']
def db_query():
query = "select count(*) from (a_table) where error_string != '';"
conn = psycopg2.connect(database=db, user=user, password=password, host=host)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute(query, tables)
output = cur.fetchall()
conn.close()
return output
答案 0 :(得分:1)
我没有使用过postgresql,所以你可能还想把它作为参考:How to store count values in python。
话虽如此,将代码重新排列成这样的东西。请务必将conn
设为全局,这样您就不必多次建立连接,并确保同时关闭cur
:
conn = None
def driverFunc():
global conn
try:
conn = psycopg2.connect(database=db, user=user, password=password, host=host)
tables = ['table1', 'table2']
countDict = {}
for thisTable in tables:
db_query(thisTable, countDict)
finally:
if not conn == None:
conn.close()
def db_query(tableName, countDict):
# Beware of SQL injection with the following line:
query = "select count(*) from " + tableName + " where error_string != '';"
cur = None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute(query)
countDict[tableName] = int(cur.fetchone())
finally:
if not cur == None:
cur.close()