我有一个 utf8 编码的 MySQL 数据库。它包含一个值为“sauté”的行。注意 e 上的重音。
当我使用 Django 应用程序选择此数据时,它会正确检测到 é。但是,当我将其作为 Python 程序执行时,此信息(特殊的 e)似乎丢失了。
我尝试了编码和解码的各种组合以及“from future import unicode_literals”,并将“u”放在 sauté 字符串前面,并将 u 放在查询字符串前面。没有运气。如何从我的数据库(使用 Python)中正确获取此信息并对其进行测试?
# Connection when excute as .py: (Django is usual in settings.py)
cursor = MySQLdb.connect(host='<xxx>',user="<xxx>", passwd="<xxx>", db="<xxx>",
unix_socket = 'path/mysql.sock'
).cursor()
# Same code in Django and Python execution:
cursor.execute(select line from my_table where id = 27)
results = cursor.fetchall()
for r in results:
line = r[0]
if re.search("sauté", line):
do_something() # Should get here, but only with Django
最佳答案
感谢 JD Vangsness(在评论中)的回答。
我需要将 charset='utf8' 添加到连接参数中。
cursor = MySQLdb.connect(host='<xxx>',user="<xxx>", charset='utf8', passwd="<xxx>", db="<xxx>", unix_socket = 'path/mysql.sock').cursor()
然后我还需要制作比较字符串unicode:
u"sauté"
关于python - 在 Python 中查询时 MySQL 特殊字符丢失。 (但可以与 Django 一起使用。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857400/