python 數據庫中文亂碼

本文實例展現了一個腳本python用來轉化表配置數據xml並生成相應的解析代碼。
可是在中文編碼上出現了亂碼,現將解決方法分享出來供你們參考。
具體方法以下:python

  1. Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8)
  2. MySQL數據庫charset=utf-8
  3. Python鏈接MySQL是加上參數 charset=utf8
  4. 設置Python的默認編碼爲 utf-8 (sys.setdefaultencoding(utf-8)
    示例代碼以下:
    複製代碼 代碼以下:數據庫

    encoding=utf-8

import sys
import MySQLdb as mdbfetch

reload(sys)
sys.setdefaultencoding('utf-8')編碼

con = Nonecode

try:
con = mdb.Connect('localhost','root','jobin','zmld',charset='utf8')
cur = con.cursor()
cur.execute("show full columns from player")xml

numRows = int(cur.rowcount)

for i in range(numRows):
    row = cur.fetchone()
    comment = row[len(row) - 1]
    print comment

finally:
if con:
con.close()utf-8

相關文章
相關標籤/搜索