【问题标题】:how to code sql select string如何编写sql选择字符串
【发布时间】:2017-10-12 13:53:28
【问题描述】:

我很困惑如何在 Python 中编码。

以下代码可从 pgsql 命令行运行。

select * from consultation_tbl where consultation_status in ('S','C','R');

但是在 Python 中,我不知道如何编码。

chat_str = "\'S\',\'C\',\'R\'"
cursor.execute(" \
        SELECT * FROM consultation_tbl
        WHERE consultation_status IN ( %s )", [chat_str])

请给我一个建议。

【问题讨论】:

标签: python sql postgresql python-3.x


【解决方案1】:

首先,您可以在双引号字符串中使用单引号,这是一个有效的 Python 文字字符串:

chat_str = "'S', 'C', 'R'"

但我会这样编码:

# 1) This joins the tokens with ', ' separator. Very useful
chat_str = ', '.join(["'S'", "'C'", "'R'",])

# 2) We use the python3 format() method for strings. 
# The '{}' is replaced. See the official docs
query = "SELECT * FROM consultation_tbl
    WHERE consultation_status IN ({})".format(chat_str)

cursor.execute(query)

在这两种情况下,结果字符串是等价的。

【讨论】:

  • 感谢您的建议。但我得到了以下错误。 django.db.utils.ProgrammingError: column "s" does not exist LINE 1: ...ation_tbl WHERE consultation_status IN (S, C, R)我该如何解决?
  • 您的代码中似乎有 %s 而不是 {} 占位符
  • 感谢您的回复。我在我的代码中使用 {}。我复制你的代码并粘贴它。怎么了?
  • 你有没有调试过这个来检查哪个是结果字符串?我需要看看 postgresql 得到了什么。
  • 如果我使用 postgresql,我可能必须使用 %s。 “{}”在我的代码中不起作用。
【解决方案2】:

通常您不希望使用手动替换字符串将 data 放入查询中——python sql api 允许您传入一个元组,它将为您清理并放入防止sql注入。话虽如此,因为 IN 子句中的参数列表的长度可能是动态的,因此您可能仍需要字符串替换来创建模板查询。我经常看到它看起来像这样:

char_list = ['S', 'C', 'R' ]
qry = "SELECT * FROM consultation_tbl WHERE consultation_status IN ( %s )"
qry %= ",".join("%s" for x in range(len(char_list)))

cursor.execute(qry, chars)

【讨论】:

  • 感谢您的建议。字符来自哪里?
猜你喜欢
  • 1970-01-01
  • 2015-07-08
  • 2018-03-14
  • 2013-10-06
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
相关资源
最近更新 更多