ASH84

Software Engineer/Developer, co-founder of Payhere. Ex-Banksalad. Intereseted in iteroperability, bootstrap company, writting.

python mysqldb DictCursor 이용하기

created:2015-01-29
updated:2015-07-03
edit

아무래도 제일많이 사용하는게 mysql 이고 python 으로 연동하기 위해서 MySQLdb 를 사용하는데 맨날 기존 cursor를 이용해서 데이터를 가져오곤 했다. 

((2L, ‘test’, ‘Test’, ‘{test}’, datetime.datetime(2015, 1, 6, 13, 26, 45), (..))

그러다 보면 위의 결과처럼 튜플(tuple)의 형태로 나오게 되는데 사실 컬럼명이 필요한 경우들이 있다. 예를들면, 공통적으로 저장프로시저를 호출하고 결과를 리턴하는 함수를 만들때는 프로시저에 종속적이지 않게 하기 위해서는 컬럼명을 키값으로 잡아서 결과와 함께 리턴해 주는게 낫다. 그래서 어떻게 하면 컬럼명을 가져올수 있을까 살펴보니, DictCursor 라는 것이 있다. 

BaseCursor
The base class for Cursor objects. This does not raise Warnings.
CursorStoreResultMixIn
Causes the Cursor to use the mysqlstoreresult() function to get the query result. The entire result set is stored on the client side.
CursorUseResultMixIn
Causes the cursor to use the mysqluseresult() function to get the query result. The result set is stored on the server side and is transferred row by row using fetch operations.
CursorTupleRowsMixIn
Causes the cursor to return rows as a tuple of the column values.
CursorDictRowsMixIn

Causes the cursor to return rows as a dictionary, where the keys are column names and the values are column values. Note that if the column names are not unique, i.e., you are selecting from two tables that share column names, some of them will be rewritten as table.column. This can be avoided by using the SQL AS keyword. (This is yet-another reason not to use * in SQL queries, particularly where JOIN is involved.)

Cursor
The default cursor class. This class is composed of CursorWarningMixIn, CursorStoreResultMixIn, CursorTupleRowsMixIn, and BaseCursor, i.e. it raises Warning, usesmysqlstoreresult(), and returns rows as tuples.
DictCursor
Like Cursor except it returns rows as dictionaries.
SSCursor
A “server-side” cursor. Like Cursor but uses CursorUseResultMixIn. Use only if you are dealing with potentially large result sets.
SSDictCursor
Like SSCursor except it returns rows as dictionaries.
위의 자료에서 보면 다양한 커서(cursor)들이 있는데 그 중에서 기본으로 사용하는 것은 여러 커서로 구성된 클래스이다. 특히 CursorTupleRowsMixIn 이 포함되어 있어서 기본적으로 fectchall() 시 결과가 튜플(tuple) 기반으로 출력되게 되는 것이다. 다음과 같이 처음 커서 생성시에 DictCursor를 지정하게 되면 튜플 기반이 아니라 사전(dict) 기반으로 출력이 되는 것을 확인할 수가 있다. 

({‘Data’: ‘{test}’, ‘seqNo’: 2L, ‘Date’: datetime.datetime(2015, 1, 6, 13, 26, 45), ‘Name‘: ‘test’, ‘ID’: ‘Test’}. {…})

2013/08/04 – [Programming/DB] – (mysql) mac 에서 mysql삭제하기.

2013/07/09 – [Programming/DB] – (stackoverflow) how to improve select performance in mysql?

2013/07/04 – [Programming/DB] – (mysql) mysqldump 을 이용한 백업 스크립트

2013/06/28 – [Programming/DB] – (mysql) insert 시간 자동 추가하기

2013/06/26 – [Programming/DB] – (mysql) Data truncation: Data too long for column ‘xxx’ at row 1

2012/11/07 – [Programming/iOS] – (iOS) iOS앱 – mysql 연동, 이렇게 하면 쉽다.

2012/10/31 – [Technique] – mac에 mysql 설치 관련 링크 정리, 이것만 알면돼!!


#cursor  #dev  #dictcursor  #MySQL  #mysqldb  #Python