2013-09-24 4 views
0

문제 : 올바른 방법으로 쿼리를 실행하여 매핑 된 사전을 반환하는 방법을 알아낼 수 없습니다. 쿼리는 여러 테이블의 개수를 사용합니다.여러 쿼리를 기반으로 매핑 된 사전을 반환하십시오.

나는 PostgreSQL 데이터베이스에 대한 psycopg2를 사용하고, 나는이 카운트 하루 델타에 일에 대한 보고서를 작성하는 결과를 사용하는 것입니다.

사람이 여러 쿼리를 실행하고 내가 비교를 위해 사용할 수있는 사전을 반환하는 방법에 대한 예를 제공 할 수 있음을 감안할 때? 감사! 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 

답변

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() 
+0

감사합니다. psycopg2 모듈 설명서는 쿼리를 실행할 때 문자열 연결을 권장하지 않습니다. [Psycopg2 Documentation] (http://initd.org/psycopg/docs/usage.html) –

+0

나는 당신이 코멘트에 이것을 인정했다고 생각한다. –

+0

이것은 매우 도움이되는 것으로 끝났지 만, 쿼리의 문자열 연결을 대체하는 '적절한'방법을 찾아내는 것이 아니었지만 공용이 아니기 때문에이 충분할 것입니다. 감사! –

관련 문제