【问题标题】:Handle apostrophe in query string using python使用python处理查询字符串中的撇号
【发布时间】:2019-03-13 18:47:35
【问题描述】:

我正在尝试使用 Python 查询 Redshift。 我正在生成一个查询字符串,如下所示: 我正在使用psycopg2 作为库来建立连接。

Select lat, lon, gender from table_x where x_name = "namestring"

如果我的姓名字符串包含',则查询字符串将无法执行。

有人能告诉我避免这个错误的方法吗?我有一个大约 25k 名称的列表,因此不能使用 \' 转义每个名称。

【问题讨论】:

  • 如果你在遍历你的名字字符串,你不能在执行查询之前转义那里的引号吗?
  • 转义单引号的 ANSI 标准方法是将其加倍,即在查询字符串中使用 ''

标签: python sql string python-3.x amazon-redshift


【解决方案1】:

使用http://initd.org/psycopg/docs/sql.html 中强烈建议的参数化查询

# somethin along the lines of this should work:

from psycopg2 import sql

names = [ "A", "McDiff", "Old'McDonal"]

for n in names:
    cur.execute(sql.SQL("Select lat, lon, gender from {} where x_name = %s")
                .format(sql.Identifier('table_x')),[n])

这避免了在使用参数化查询构造而不是字符串连接时自引用的问题。


请参阅Little Bobby Tables / Exploit of a Mom 和 google sql injection 以了解不进行字符串连接的其他原因。

【讨论】:

  • 当表名是连接子句时,你能帮忙解决一下这个场景吗? sql.identifier 在连接的情况下如何工作?
  • @SumedhaNagpal 不,我不能。请参阅文档。你所问的(关于'销毁你的查询)在任何数量的 Sql-Like 查询中都很常见 - 使用参数化查询是解决这个问题的方法。至于联合查询,使用psycopg提供的API,研究一下。
【解决方案2】:

您可以在字符串中使用单引号,并使用参数化字符串替换您的值。

QUERY = """select lat, lon, gender from table_x where x_name = '{namestring}'"""
for namestring in list_of_namestrings:
    cur.execute(QUERY.format(namestring=namestring) 

这应该可以解决您的目的,您可以根据需要使 QUERY 复杂,并使用 .format() 进行所需的替换

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2015-04-22
    • 2017-07-26
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多