3 回答

TA贡献1806条经验 获得超5个赞
假设您正在使用MySQLdb,则在创建连接时需要传递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的组合对于连接是很冗长的,但是即使对于标准库之外的最有用的python库,我也很自然地产生偏执,所以我尝试明确地使bug易于发现库是否发生了变化。

TA贡献1900条经验 获得超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
添加回答
举报