【发布时间】:2019-03-25 17:33:07
【问题描述】:
我尝试从插入查询中选择返回值:
HOST_INSERT_QUERY = (
Host.__table__.insert()
.values(
name=bindparam("name"),
source=bindparam("source"),
type=bindparam("type")
)
.returning(Host.__table__.c.id)
)
result = db_conn.execute(HOST_INSERT_QUERY, values)
我从 db.echo 中看到的:
info sqlalchemy.engine.base.Engine INSERT INTO hosts (name, source, type) VALUES ( %(name)s, %(source)s, %(type)s) RETURNING hosts.id
info sqlalchemy.engine.base.Engine ({ 'name': 'hhh', 'source': '["import"]', 'type': 'host'},{...})
debug: Added 2 hosts
确实有效。主机插入数据库,但我在调试器中看到一些问题;结果(ResultProxy)有:
rowcount = 2 #right!
is_insert = True #right!
return_rows=False #WHYYYY????????
如果我尝试:
result.fetсhall()
AttributeError: 'ResultProxy' object has no attribute 'fetсhall'
版本:
- SQLAlchemy 1.3.1
- psycopg 二进制 2.7.7
注意! 此代码仅在插入单个记录时有效。插入多行时,无法将值拉出RETURNING。
【问题讨论】:
-
在调用
fetchall方法之前,可能已经读取了光标。对这个查询似乎没什么好奇。 -
也许吧。 result = db_conn.execute(HOST_INSERT_QUERY, values) 这种情况下会得到更合适的错误信息:AttributeError: 'ResultProxy' object has no attribute 'fetсhall'
标签: python postgresql sqlalchemy psycopg2