如何从 Python 中的 SQL 查询的字符串中删除引号?

How to remove the quotes from a string for SQL query in Python?

我有一本数据库名称字典。我从字典里取了个名字

database_name = database_dict[i]

假设 database_name 的值是 'foo'

使用 Psycopg2 我正在执行一个语句:

cur.execute("INSERT INTO %s VALUES(...);", database_name)

我在 foo 处收到语法错误,因为它应该是 "INSERT INTO foo VALUES" 而不是 "INSERT INTO 'foo' VALUES"

关于如何为 table 的名称传递字符串值并删除单引号,有什么建议吗?我应该在我的数据库字典值中放置一个转义字符吗?

编辑:这里有更近的东西:How do I remove single quotes from a table in postgresql?

但我无法使用 REMOVE 让它工作。它在 remove 语句中的单引号处给出了语法错误。

如果 database_name"'foo'"

要删除单引号:

database_name = database_name.replace("'", "")

SQL 查询的结构组件,例如 table 和字段名称,无法在您尝试 cursor.execute(query, params) 的第二个参数时进行参数化。只能参数化 numeric/literal 个数据值。

考虑将 database_name 变量插入到 SQL 查询字符串中,但使用 psycopg2 的 sqlIdentifier()str.format 安全地这样做:

from psycopg2 import sql
...

cur.execute(sql.SQL('INSERT INTO {} VALUES(...)').format(sql.Identifier(database_name)))

在您的情况下有效 parameterizaiton 将绑定在 VALUES(...) 中传递的数据值在追加查询中,例如 VALUES(%s, %s, %s)。或者在其他查询中:

"SELECT %s AS NewColumn..."

"...WHERE fieldname = %s OR otherfield IN (%s, %s, %s)"

"...HAVING Max(NumColumn) >= %s"
from psycopg2.extensions import AsIs
cur.execute("INSERT INTO %s VALUES(...);", AsIs(database_name))

http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.AsIs

顺便说一句,这不是数据库名称,它是一个 table 名称。

注意:我没有用过psycopg2,这是我从类似的数据库库中了解到的。

A table 名称是一个标识符,它们的引号和转义方式与值不同。我相信你应该使用 psycopg2.extensions.quote_ident(str, scope) to quote and escape it. I believe it uses the PostgreSQL function PQescapeIdentifier().

PQescapeIdentifier escapes a string for use as an SQL identifier, such as a table, column, or function name. This is useful when a user-supplied identifier might contain special characters that would otherwise not be interpreted as part of the identifier by the SQL parser, or when the identifier might contain upper case characters whose case should be preserved.

然后它将被引用和转义,并且可以使用正常的字符串操作安全地添加到 SQL 字符串,而不会冒 SQL injection attack 的风险,或者使用 AsIs(quote_ident(database_name)) 作为 .execute.