gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:56:55 24 4
gpt4 key购买 nike

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

我想使用一个接受变量并在 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.

关于python - 使用 PostgreSQL 时如何将变量插入 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57517522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com