#!/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)