使用 PostgreSQL 时如何将变量插入 python

How to insert variables into python when using PostgreSQL

所以我确定我的问题已经有解决方案,但我还没有看到可以帮助我清楚地理解它的答案。

我想使用一个接受变量并在 PostgreSQL select 语句中使用该变量的函数。

这是我的尝试,但不正确。

def some_func(var):
    cursor.execute("SELECT * FROM table WHERE attribute = %s",var)
    return

所以如果我要运行some_func("height"),我希望postgres语句执行如下:

SELECT * FROM table WHERE attribute = 'height';

我收到错误:

TypeError: not all arguments converted during string formatting

the documentation

Parameters may be provided as sequence or mapping and will be bound to variables in the operation.

将变量放入序列中:

cursor.execute("SELECT * FROM table WHERE attribute = %s", [var])

另读Passing parameters to SQL queries.

字符串格式化时,不要使用逗号,而是另一个百分比。在您的情况下,这将是:

def some_func(var):
    cursor.execute("SELECT * FROM table WHERE attribute = %s" % var)
    return

这应该可以实现您的目标,如果没有,请发表评论!