9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonのMySQLdbでUTF-8の日本語文字を扱う。

Last updated at Posted at 2016-01-02

PythonでMySQLdbを通して日本語が含まれるレコードをぶっこ抜くのにunicodeになりやがる。

Python + MySQLで様々にググっても、たぶん簡単すぎて誰も書いてやがらないのでメモります。ポイントはconnector.cursorclass = MySQLdb.cursors.DictCursorのところなんだろうと思う。

sample.py
# -*- coding: utf-8 -*- 
# coding: UTF-8

import MySQLdb
from MySQLdb.cursors import DictCursor
if __name__ == "__main__":
    connector = MySQLdb.connect(host='localhost',db="dbname",user="user",passwd="password", charset="utf8")
    connector.cursorclass = MySQLdb.cursors.DictCursor
    cursor = connector.cursor()
    cursor.execute("SET NAMES utf8")
    cursor.execute = connector.cursor()
    cursor.execute.execute('SELECT * FROM sample limit 10')
    res = cursor.execute.fetchall()
    for row in res:
     print row['users']
    cursor.close()
    connector.close()
9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?