python - 将 python 字典传递给 psycopg2 游标

标签 python postgresql psycopg2

我需要调用一个 PostgreSQL 8.4 函数,它需要来自 Python 的 17 个输入参数。这些值存储在字典中。所以我可以写:

cur.execute("SELECT add_user(%s, %s, %s, %s, %s, %s, %s, .......)", user["nr"], user['email']...)

是否可以自动将字典中的值映射到函数参数(与字典中的键同名)?

类似于:

cur.execute("SELECT add_user(*magic-here*)", user)

最佳答案

应该使用以下语法:

cur.execute("SELECT add_user(%(nr)s, %(email)s, ...) ...", user)

感谢Thiefmaster提供对我最初在这里的内容的更正: 参数的 %(keyname)s 格式只是 Python Database API 2.0 中定义的格式之一。 - 查看 paramstyle 的文档。遗憾的是,其他 DB API 2.0 数据库适配器可能不支持此语法。

有关类似问题的答案,但有额外的 xkcd 引用,请参阅:Parameterized queries with psycopg2 / Python DB-API and PostgreSQL

关于python - 将 python 字典传递给 psycopg2 游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139700/

相关文章:

python - 从 DictRow 中删除一个项目

python - 无法在新的 docker 容器上安装 psycopg2-binary

python - 将多个时间戳行折叠为单个时间戳行

python - 减去具有不同列类型的 Pandas 中的行

python - 不能在不改变颜色的情况下覆盖面膜?

Python 和 RFC 3339 时间戳

postgresql - 如何恢复/倒带我的 PostgreSQL 数据库

postgresql - Postgres : how to start a procedure right after database start?

python-3.x - 使用 psycopg2 将 git 修订散列 (SHA-1) 写入 PostgreSQL 数据库

postgresql - 使用 PostgreSQL 触发器对数据进行动态审计