3 回答

TA貢獻(xiàn)1806條經(jīng)驗 獲得超5個贊
假設(shè)您正在使用MySQLdb,則在創(chuàng)建連接時需要傳遞use_unicode = True和charset =“ utf8”。
更新:如果我對測試表運行以下命令,我會得到-
>>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8")
>>> c = db.cursor()
>>> c.execute("INSERT INTO last_names VALUES(%s)", (u'M\xfcller', ))
1L
>>> c.execute("SELECT * FROM last_names")
1L
>>> print c.fetchall()
(('M\xc3\xbcller',),)
這是“正確的方法”,字符已正確存儲和檢索,您的朋友編寫php腳本只是在輸出時未正確處理編碼。
正如Rob所指出的那樣,use_unicode和charset的組合對于連接是很冗長的,但是即使對于標(biāo)準(zhǔn)庫之外的最有用的python庫,我也很自然地產(chǎn)生偏執(zhí),所以我嘗試明確地使bug易于發(fā)現(xiàn)庫是否發(fā)生了變化。

TA貢獻(xiàn)1900條經(jīng)驗 獲得超5個贊
import MySQLdb
# connect to the database
db = MySQLdb.connect("****", "****", "****", "****") #don't use charset here
# setup a cursor object using cursor() method
cursor = db.cursor()
cursor.execute("SET NAMES utf8mb4;") #or utf8 or any other charset you want to handle
cursor.execute("SET CHARACTER SET utf8mb4;") #same as above
cursor.execute("SET character_set_connection=utf8mb4;") #same as above
# run a SQL question
cursor.execute("****")
#and make sure the MySQL settings are correct, data too
添加回答
舉報