python - 在 Python 中查询时 MySQL 特殊字符丢失。 (但可以与 Django 一起使用。)

标签 python mysql django

我有一个 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/

相关文章:

django - 从 Django wsgi.py 文件访问 Apache SetEnv 变量

python - Heroku 的 Procfile 的正确目录

python - Django - 按管理员中的用户配置文件字段排序

javascript - Node/Mysql 异步数据

php - 从指定边界内的数据库获取坐标( map 角)

python - 在 Django 中使用 inspectdb 时出错

带有不同和 order_by 的 Django 查询

python - 如何在不制作新的.jpg文件的情况下使用opencv从相机获取图像

python - 如何让Eclipse(pydev)打开文件时自动折叠所有注释?

c# - 如何在 ASP.NET MVC 中显示具有相同 ID 的所有行?