Python Mysql 한글깨짐 인코딩 문제 해결.

 

저는 파이썬 2.7을 사용하고 있습니다. 아직 3.*는 여러가지 모듈이 지원되지 않아 당분간은 2.*를 계속 유지할 계획입니다.

Python 2.7 에서 MySQL 사용하는 방법입니다.

먼저  MySQL-python-1.2.3.win32-py2.7.exe 설치 합니다.
http://code.google.com/p/soemin/downloads/detail?name=MySQL-python-1.2.3.win32-py2.7.exe&can=2&q=

# DB접속
>>> import MySQLdb

# charset과 use_unicode 는 문자 인코딩 관련 설정
>>> db = MySQLdb.connect(db='db명', user='아이디', passwd='패스워드', host='아이피', charset='euckr', use_unicode=True)

# 커서생성
cur = db.cursor()

# SQL 문 실행
cur.execute('''
SQL 문장
''')

# select
cursor.execute('select ....')
cursor.rowcount; # 결과 행수
cursor.description; # 각 필드 특징 (필드명,데이터형_코드, 표시크기, 내부크기, 정확도, 비율, nullable)

cursor.fetchone(); # 결과 한개, 더이상 레코드 없으면 None
curor.fetchmany(n); # n 개의 결과. 튜플
cursor.fetchall(); # 남은 결과 전체. 튜플

# 튜플이 아닌 사전 형식으로 필드 가져오기
cursor = db.cursor(MySQLdb.cursors.DictCursor)
# 위 형태로 커서를 가져오면 fetch*() 메소드 실행 결과가 필드명을 키로 한 사전이다.

커밋/롤백
db.commit()
db.rollback()

# DB 작업 종료
cursor.close()
db.close()

 

기타 인코딩 방법에

import codes

unicode(‘encoding target string’, ‘utf-8’).encode(‘euc-kr’)

과 같이 하는 방법도 있다.

이것은 텍스트를 인코딩 하는 방법으로 타겟 db와의 연동시에는 별도의 과정이 들어가는 것 같아. 그래서 위으 박스와 같은 과정을 거쳐야한다.

 

end.

Leave a Reply

Your email address will not be published. Required fields are marked *

 characters available