Python Psycopg2-在where子句中传递变量

Python Psycopg2-在where子句中传递变量,python,amazon-redshift,psycopg2,Python,Amazon Redshift,Psycopg2,我尝试在Python中运行SQL脚本,在where子句中传递一个变量,如下所示: cursor.execute(f"""select * from table where type = variable_value""") 在上面的查询中,variable\u value具有我试图在where子句中使用的值。但是,我得到一个错误:根据psycopg2文档,函数将变量作为额外参数 cursor.execute("""select * from table where type = %(value

我尝试在Python中运行SQL脚本,在where子句中传递一个变量,如下所示:

cursor.execute(f"""select * from table where type = variable_value""")

在上面的查询中,
variable\u value
具有我试图在where子句中使用的值。但是,我得到一个错误:根据psycopg2文档,函数将变量作为额外参数

cursor.execute("""select * from table where type = %(value)s """, {"value": variable_value})
更多的例子

另外,请仔细阅读有关的部分-要点是,您不应该在查询中引用参数,
execute
函数将处理这些问题,以防止有害SQL的注入


还要解释您得到的错误-您发送的查询正在比较两个标识符(
type
variable\u value
)。
不包含
变量值
列,因此出现错误

我相信,您打算使用来构造查询,但是您忘记了
{}
。它的工作原理如下:

cursor.execute(f"""select * from table where type = '{variable_value}'""")
⚠️ 但是由于前面提到的SQL注入,这不是推荐的方法