解决Python操作MySQL中文乱码的问题

原始代码:

import os, sys, string
import MySQLdb

MYSQL_HOST = 'localhost'
MYSQL_PORT = '3306'
MYSQL_USER = 'root'
MYSQL_PASS = ''
MYSQL_DB = 'app_hwms'


def main():
    try:
        conn = MySQLdb.connect(host=MYSQL_HOST,user=MYSQL_USER ,passwd=MYSQL_PASS,db=MYSQL_DB)
    except Exception, e:
        print e
        sys.exit()
    
    c = conn.cursor()
    text = u'中文'
    print text
    c.execute("insert into test (test) values( '%s' )" % (text))
    c.execute('select * from test')
    msgs = list(c.fetchall())

    print msgs

if __name__ == '__main__':
    main()

出现以下报错:

而直接操作mysql:

是有中文的。

 

解决办法:

1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
2 Python连接MySQL是加上参数 charset=utf8 

3 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

 

修改后代码:


#encoding=utf-8

import os, sys, string
import MySQLdb

MYSQL_HOST = 'localhost'
MYSQL_PORT = '3306'
MYSQL_USER = 'root'
MYSQL_PASS = ''
MYSQL_DB = 'app_hwms'

reload(sys)
sys.setdefaultencoding('utf-8')

def main():
    try:
        conn = MySQLdb.connect(host=MYSQL_HOST,user=MYSQL_USER ,passwd=MYSQL_PASS,db=MYSQL_DB,charset='utf8')
    except Exception, e:
        print e
        sys.exit()
    
    c = conn.cursor()
    text = u'中文'
    print text
    c.execute("insert into test (test) values( '%s' )" % (text))
    c.execute('select * from test')
    msgs = list(c.fetchall())

    print msgs

if __name__ == '__main__':
    main()

重新执行的结果:

 

而用flask,在html中原本显示??的中文字符也可以正确的显示了。

 

posted @ 2015-03-05 13:49  AminHuang  Views(1709)  Comments(0Edit  收藏  举报