python - Sqlalchemy:engine.execute() 的 postgresql paramstyle

标签 python postgresql python-3.x sqlalchemy

我使用 sqlalchemy 连接到 postgresql。当我尝试这段代码时:

e = create_engine('')
r = e.execute("select ?", 5)

它给了我:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at end of input

对应http://www.sqlalchemy.org/docs/core/connections.html?highlight=engine#sqlalchemy.engine.base.Connection.execute有不同类型的参数样式... 经过更深入的研究,我发现 postgresql 方言的默认参数样式是“pyformat”。

有人能告诉我如何在一些例子中使用这个 pyformat 吗? 我只想使用占位符或命名占位符来构成 sql 语句。

我试过:

e.execute("select %s, %s;", "test", "test2")

但这也不起作用。

谢谢

编辑: 当然,我将有效的连接字符串传递给 create_engine 方法:-)

最佳答案

您链接到的文档直接链接到 PEP 249,它向您展示了不同的样式。

关于 pyformat,它说:

'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s'

这就是您需要使用的。

通过谷歌搜索“DBAPI pyformat”,第二个链接是指向 psycopg2 documentation 的链接。 .在提到它使用 pyformat 之后,有一个“另见”链接到 a page with loads of examples .

如何使用它的示例在您的原始链接中:

e.execute("select %s, %s;", ("param1", "test"), ("param2", "test2"))

你也可以使用这个语法:

e.execute("select %(param1)s, %(param2)s;", param1="test", param2="test2"))

哪个更好。

关于python - Sqlalchemy:engine.execute() 的 postgresql paramstyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7077427/

相关文章:

postgresql - 使用 postgreSQL 创建表

python - 将函数中定义的变量的值分配给单独函数中的变量

python - 用 pandas 并行读取 CSV 会产生巨大的内存泄漏/进程僵尸

python - 用名称替换标题

python - Keras RNN(GRU、LSTM)产生平稳期然后改进

sql - 将 double 转换为文本的 Postgres 创建 '1.50000000000'

python-3.x - 通过迭代字符串,如何提取更多索引和相应的值?

Python - 从复杂对象的有序列表中删除重复项?

python - 12 月至 1 月的平均日期

ruby-on-rails - 使用 Rails 将几何字段添加到 PostGIS