關於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