본문 바로가기
파이썬

파이썬 python mysql.connector DictCursor?

by º기록 2020. 12. 18.
반응형

Python mysqldb 에서는 다음과 같이 커서를 사전 커서로 선언 할 수 있습니다.

cursor = db.cursor(MySQLdb.cursors.DictCursor) 

이렇게하면 다음과 같은 이름으로 cursor 루프의 열을 참조 할 수 있습니다.

for row in cursor:   # Using the cursor as iterator 
    city = row["city"]
    state = row["state"]

이 MySQL 커넥터를 사용하여 사전 커서를 만들 수 있습니까?


그들의 예제는 튜플 만 반환합니다.

나는 MySQL의 제작자가 결국 우리를 위해 이것을 할 것이라고 상상합니다.

 

해결 방법

 

가능한 해결책은 다음과 같이 MySQLCursor 클래스를 서브 클래 싱하는 것입니다.

class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
    def _row_to_python(self, rowdata, desc=None):
        row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
        if row:
            return dict(zip(self.column_names, row))
        return None

db = mysql.connector.connect(user='root', database='test')

cursor = db.cursor(cursor_class=MySQLCursorDict)

이제 _row_to_python () 메서드는 tuple 대신 dictionary 를 반환합니다.

나는 이것을 mysql 포럼에서 찾았고 mysql 개발자가 직접 게시했다고 생각합니다. 언젠가 mysql 커넥터 패키지에 추가하기를 바랍니다.

나는 이것을 테스트했고 작동합니다.

업데이트 : Karl M.W가 아래에서 언급했듯이이 하위 클래스는 더 이상 mysql.connector v2에서 필요하지 않습니다. mysql.connector가 업데이트되었으며 이제 다음 옵션을 사용하여 사전 커서를 활성화 할 수 있습니다.

cursor = db.cursor(dictionary=True)

 

참조 페이지 https://stackoverflow.com/questions/22769873

 

 

반응형

댓글