【问题标题】:Python Django mysqldb select with unicode valuePython Django mysqldb 选择带有 unicode 值
【发布时间】:2017-06-08 04:16:56
【问题描述】:

当我使用这个子句时,一切都是正确的。 find 这里是モンキー・D・ルフィ

   sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');" % find.encode('utf-8')
   self.db.execute(sql_fmt)

但是当我使用这个子句时,发生了错误。 find 在这里是(モンキー・D・ルフィ)('モンキー・D・ルフィ')

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in %s;"
self.db.execute(sql_fmt, find)

错误

ProgrammingError: (1064, "您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,了解在 ''(\'\xe3\x83\xa2\xe3\x83 附近使用的正确语法\xb3\xe3\x82\xad\xe3\x83\xbc\xe3\x83\xbbD\xe3\x83\xbb\xe3\x83\xab\xe3\x83\x95\xe3\x82\xa3\')''第 1 行") 对于这个子句,发生了错误。 find 这里是モンキー・D・ルフィ

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in ('%s');"
self.db.execute(sql_fmt, find)

对于这个子句,一切都很顺利。 find 这里是モンキー・D・ルフィ

sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in (%s);"
self.db.execute(sql_fmt, find) 

注意:

我使用in 表示它是一组字符串,而不仅仅是单个字符串。

【问题讨论】:

  • miss "" around String ~> 很多是" some text"
  • @NamNguyễn 你的意思是把(モンキー・D・ルフィ)改成("モンキー・D・ルフィ")
  • 你试过 find.encode('utf-8') 吗?
  • @Tiny.D 我试过了,同样的错误。
  • 您在此处找到的字符串类似于"(モンキー・D・ルフィ) or ('モンキー・D・ルフィ')"?

标签: python mysql unicode


【解决方案1】:

您可能在查询中缺少“”

# it should be: 
select * from characters where name = "some string"
#OR 
select * from characters where name in "some string"
# In your case:
sql_fmt = "select name, gender, age, height, hobby, ability, popularity, voice_actor, birth_place, image from characters where name in "%s";"

或者可能是某种这种,我不使用它。

你应该使用:

res = Models.Objects.filter(name__in = yourlist)
# Django help you all the way to convert it to Query

【讨论】:

  • 我使用in,这意味着它是一组字符串,而不是单个字符串。
  • 我建议您使用 Django 查询(不是 RAW 查询)。如果没有,我相信你不是在询问 django-query...删除 django 的标签
  • 标签已被删除。
  • 使用IN时需要括号。
猜你喜欢
  • 2011-11-10
  • 2015-02-19
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2011-09-20
  • 1970-01-01
  • 2013-11-07
相关资源
最近更新 更多