首页 > 数据库技术 > 详细

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

时间:2015-03-05 14:16:26      阅读:289      评论:0      收藏:0      [点我收藏+]

原始代码:

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中原本显示??的中文字符也可以正确的显示了。

 

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

原文:http://www.cnblogs.com/AminHuang/p/4315641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!