首页 > 解决方案 > 使用python参数化的postgresql select语句

问题描述

sql="select %s,tablename from pg_table_def where tablename like (%s)"

data=("schemaname","abc",)

cur.execute(sql,data)

如果我如上所述传递一个值,则选择将其作为字符串。这不是本意。

如果我尝试

data=(schemaname,"abc",)

然后它显示错误global name 'schemaname' is not defined

标签: pythonpostgresqlaws-lambdaamazon-redshiftpsycopg2

解决方案


您不能以这种方式参数化对象名称(在本例中为列名称)。您可以改为使用字符串操作:

column = "schemaname"
sql = "select {}, tablename from pg_table_def where tablename like (%s)".format(column) 
data= ("abc",)

cur.execute(sql,data)

推荐阅读