利用python寫程序從mysql中讀取數據寫入excel中,結果發現中文顯示亂碼。
網上搜索了下方法:
Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8), 同時文件保存的格式也應該是utf8
MySQL數據庫charset=utf-8 ,數據庫的編碼必須是utf8
python連接MySQL時加上編碼參數 conn = MySQLdb.Connection(host='localhost', user='root', passwd='123', db='test',charset='utf8')
設置Python默認編碼(個人感覺此無太多意義)
reload(sys)
sys.setdefaultencoding('utf-8')
二種
tmp = str(row[2])
tmp = tmp.decode('utf-8')
我的實際情況是將連接字符串加上charset=‘utf8’,成功。如下:(當然我的python文件設置編碼為utf-8,mysql的編碼也是utf-8)
MySQLdb.Connection(host='localhost', user='root', passwd='123', db='test',charset='utf8')