python - 插入不适用于 SQLAlchemy 数据库 session

标签 python sqlalchemy pyramid pylons

为什么没有插入记录?返回了一个 id,但是当我检查数据库时没有新记录。

来自 models.py

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

views.py

DBSession.execute(text('INSERT INTO (a,b,c) VALUES (\'a\',\'b\',\'c\') RETURNING id'), params=dict(a=a,b=b,c=c))

我已经尝试使用 transaction.commit() 提交,它没有收到错误但没有插入记录。 result.fetchone()[0] 正在获取一个 id。

DBSession.commit 获取

assert self.transaction_manager.get().status == ZopeStatus.COMMITTING, "Transaction must be committed using the transaction manager"

最佳答案

这是因为您没有使用 ORM 来插入新行,因此事务不知道它应该自己提交,因为事务状态未标记为脏。

在您 DBSession.execute views.py 中的查询之后放置以下代码。

from zope.sqlalchemy import mark_changed
session = DBSession()
session.execute(...your query...)
mark_changed(session)

此时事务应该能够正确提交您的查询,或者使用 ORM 插入新行。

这里有更多关于这个主题的内容:

https://pypi.python.org/pypi/zope.sqlalchemy/0.7.4#id15

By default, zope.sqlalchemy puts sessions in an 'active' state when they are first used. ORM write operations automatically move the session into a 'changed' state. This avoids unnecessary database commits. Sometimes it is necessary to interact with the database directly through SQL. It is not possible to guess whether such an operation is a read or a write. Therefore we must manually mark the session as changed when manual SQL statements write to the DB.

关于python - 插入不适用于 SQLAlchemy 数据库 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21058721/

相关文章:

jquery-mobile - jquery mobile js include 正在覆盖 bootstrap css - 我该如何修复?

python - 使用 SQLAlchemy DBSession 对 Pyramid View 进行单元测试的正确方法是什么?

python 2.7 vs 3编码解码字节字符串

python - Python屏幕共享

python - SQLAlchemy 急切加载递归模型

python - 为什么 SQLAlchemy 不创建串行列?

python - 如何找出与矩阵的特定特征值对应的特征向量?

python - 从 git 安装 Python 包 pathos

python - 如何在没有数据库查询的情况下找到 sqlalchemy 远程端对象的类或类名?

python - Pyramid 项目内的外部 iFrame。更新后没有刷新