python操作mysql中文顯示亂碼的解決方法
更新時間:2014年10月11日 10:01:11 投稿:shichen2014
這篇文章主要介紹了python操作mysql中文顯示亂碼的解決方法,是Python數(shù)據(jù)庫程序設計中經(jīng)常會遇到的問題,非常具有實用價值,需要的朋友可以參考下
本文實例展示了一個腳本python用來轉化表配置數(shù)據(jù)xml并生成相應的解析代碼。
但是在中文編碼上出現(xiàn)了亂碼,現(xiàn)將解決方法分享出來供大家參考。
具體方法如下:
1. Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8)
2. MySQL數(shù)據(jù)庫charset=utf-8
3. Python連接MySQL是加上參數(shù) charset=utf8
4. 設置Python的默認編碼為 utf-8 (sys.setdefaultencoding(utf-8)
示例代碼如下:
復制代碼 代碼如下:
#encoding=utf-8
import sys
import MySQLdb as mdb
reload(sys)
sys.setdefaultencoding('utf-8')
con = None
try:
con = mdb.Connect('localhost','root','jobin','zmld',charset='utf8')
cur = con.cursor()
cur.execute("show full columns from player")
numRows = int(cur.rowcount)
for i in range(numRows):
row = cur.fetchone()
comment = row[len(row) - 1]
print comment
finally:
if con:
con.close()
import sys
import MySQLdb as mdb
reload(sys)
sys.setdefaultencoding('utf-8')
con = None
try:
con = mdb.Connect('localhost','root','jobin','zmld',charset='utf8')
cur = con.cursor()
cur.execute("show full columns from player")
numRows = int(cur.rowcount)
for i in range(numRows):
row = cur.fetchone()
comment = row[len(row) - 1]
print comment
finally:
if con:
con.close()
希望本文所述對大家的Python程序設計有所幫助。
相關文章
Python?PaddleNLP開源實現(xiàn)快遞單信息抽取
這篇文章主要為大家介紹了Python?PaddleNLP開源項目實現(xiàn)對快遞單信息抽取,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06