這兩天看了很多關(guān)于mysql中文亂碼的問題,除了創(chuàng)建table的時候設(shè)置為utf8編碼以及修改mysql配置文件的方法外,很少有人提關(guān)于python庫中中文亂碼的處理辦法,尤其是records庫的中文亂碼問題。
文中的代碼在CentOS或者Ubuntu操作系統(tǒng)python3的環(huán)境下都測試沒問題。
基于python3使用pymysql來讀取mysql中的內(nèi)容,在connect中一定要加入charset參數(shù),否則中文在ubuntu或者centos下讀出來顯示一堆問號。
# -*- coding: utf-8 -*-
import pymysql
import config
if __name__ == '__main__':
db = pymysql.connect(config.mysql_host, config.mysql_user, config.mysql_pass, config.mysql_db, charset='utf8')
cursor = db.cursor()
sql = "select name from user"
cursor.execute(sql)
for row in cursor.fetchall():
print(row)
db.close()
records庫是requests作者 kennethreitz 寫的一個非常方便的針對各種數(shù)據(jù)庫進(jìn)行數(shù)據(jù)處理的python庫,只不過文檔和網(wǎng)上的相關(guān)內(nèi)容很少,尤其是中文的情況,如果不知道正確的使用方法很容易出現(xiàn)亂碼。
mysql4read = 'mysql://{user}:{passwd}@{host}:3306/{db}'.format(host=host, user=user, passwd=pass, db=db)
db = records.Database(mysql4read, connect_args={"charset": "utf8"})
sql = "select name from user"
for row in db.query(sql).as_dict():
print(row)
可以看到一定要在創(chuàng)建db對象的時候傳入connect_args參數(shù),否則中文很容易出現(xiàn)亂碼。