关于python2.7从数据库读取中文显示乱码的问题解决


#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import MySQLdb
import sys

str = raw_input("please input error code:")

conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='123456', db='error_code',charset='utf8')
cur = conn.cursor()

sql ="select * from error_message where code = " + "'" + str + "'"

cur.execute(sql)
data=cur.fetchall()

print "分类:"+data[0][0].encode("UTF-8"),"错误码:"+data[0][1].encode("UTF-8"),"错误描述:"+data[0][2].encode("UTF-8"),"相关业务方:"+data[0][3].encode("UTF-8")


cur.close()
conn.close()

  

 

主要有两点如下:

1、在连接数据库时要指定编码类型,如果不指定,将会报如下错误,就算第二步编码了也会出问题。

charset='utf8'

2、在输出数据的时候需要编码:data[0][0].encode("UTF-8"),如果不编码则会报错:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM