SQL 标识符替换 - 使用列名列表
SQL identifier substitution - Using a list of column names
我正在尝试 运行 形式的查询:
SELECT {} from TABLE where foo = VALUE
但我希望能够提供一个列表来替换 {}
根据 psycopg 文档,为了安全地执行此操作,您需要使用 sql.Identifier
函数,以便正确转义参数,然后执行如下操作:
SQL = sql.SQL(
"SELECT {} FROM foo WHERE bar = %s"
).format(identifier)
cursor.execute(SQL, [VALUE])
当 identifier
是单个元素时,这是有效的,但我需要它是一个任意数字。例如如果:
identifier = ["abc", "def"]
和
VALUE = 4
SQL = SELECT abc def FROM foo WHERE bar = 4
我已经为 identifier
的每个成员尝试了 运行ning sql.Identifier(x)
,但这给了 "abc""def"
,这显然是不正确的。
您需要使用 sql.join(),使其像列表理解一样工作:
from psycopg2 import sql
cols = ["abc", "def"]
query = sql.SQL(
"select {0} from {1} where abc = %s").format(
sql.SQL(', ').join([sql.Identifier(c) for c in cols]),
sql.Identifier('foo')
)
cur = conn.cursor()
print(query)
print(cur.mogrify(query, ('1', )))
cur.execute(query, ('1', ))
print (cur.rowcount, cur.fetchall())
输出:
Composed([SQL('select '), Composed([Identifier('abc'), SQL(', '), Identifier('def')]), SQL(' from '), Identifier('foo'), SQL(' where abc = %s')])
select "abc", "def" from "foo" where abc = '1'
(1, [('1', '2')])
我正在尝试 运行 形式的查询:
SELECT {} from TABLE where foo = VALUE
但我希望能够提供一个列表来替换 {}
根据 psycopg 文档,为了安全地执行此操作,您需要使用 sql.Identifier
函数,以便正确转义参数,然后执行如下操作:
SQL = sql.SQL(
"SELECT {} FROM foo WHERE bar = %s"
).format(identifier)
cursor.execute(SQL, [VALUE])
当 identifier
是单个元素时,这是有效的,但我需要它是一个任意数字。例如如果:
identifier = ["abc", "def"]
和
VALUE = 4
SQL = SELECT abc def FROM foo WHERE bar = 4
我已经为 identifier
的每个成员尝试了 运行ning sql.Identifier(x)
,但这给了 "abc""def"
,这显然是不正确的。
您需要使用 sql.join(),使其像列表理解一样工作:
from psycopg2 import sql
cols = ["abc", "def"]
query = sql.SQL(
"select {0} from {1} where abc = %s").format(
sql.SQL(', ').join([sql.Identifier(c) for c in cols]),
sql.Identifier('foo')
)
cur = conn.cursor()
print(query)
print(cur.mogrify(query, ('1', )))
cur.execute(query, ('1', ))
print (cur.rowcount, cur.fetchall())
输出:
Composed([SQL('select '), Composed([Identifier('abc'), SQL(', '), Identifier('def')]), SQL(' from '), Identifier('foo'), SQL(' where abc = %s')])
select "abc", "def" from "foo" where abc = '1'
(1, [('1', '2')])