2011-12-07 3 views
5

adbapi 쿼리에서 사전 결과를 MySQL로 반환하는 방법이 있습니까?Twisted MySQL adbapi return dictionary

[name: 'Bob', phone_number: '9123 4567'] 

기본값은 튜플을 반환합니다. 간단한 파이썬 & MySQL을 들어

['Bob', '9123 4567'] 

우리는 MySQLdb.cursors.DictCursor를 사용할 수 있습니다. 나는 그것을 해결하지만 난 더 나은 방법이 있어야한다고 생각 :하지만 어떻게 트위스트 adbapi


UPD와 함께 사용합니다. 내 솔루션 : 그냥 adbapi.ConnectionPool 클래스의 * _runInteraction * 메서드를 재정의하십시오.

class MyAdbapiConnectionPool(adbapi.ConnectionPool): 
def _runInteraction(self, interaction, *args, **kw): 
    conn = self.connectionFactory(self) 
    trans = self.transactionFactory(self, conn) 
    try: 
     result = interaction(trans, *args, **kw) 
     if(result and isinstance(result[0], (list, tuple))): 
      colnames = [c[0] for c in trans._cursor.description] 
      result = [dict(zip(colnames, item)) for item in result]   
     trans.close() 
     conn.commit() 
     return result 
    except: 
     excType, excValue, excTraceback = sys.exc_info() 
     try: 
      conn.rollback() 
     except: 
      log.err(None, 'Rollback failed') 
     raise excType, excValue, excTraceback 

답변

9

당신은 MySQLdb는 connect 함수에 cursorclass 인수의 값으로 전달하여 DictCursor를 사용하여 안내 할 수 있습니다. ConnectionPool 당신이 연결 방법을 통해 임의의 인수를 전달 할 수 있습니다 : 예 runQuery("SELECT 1") 요즘

+2

({'1': 1L},)의 결과를 생성, 쿼리를 실행하면

import MySQLdb pool = ConnectionPool("MySQLdb", ..., cursorclass=MySQLdb.cursors.DictCursor) ... 

, 당신은 튜플 대신 다시 dict를 얻을 수 있습니다 우리 이 코드를 실행하기 위해 MySQLdb.cursors를 import 할 필요가있다. –