插入不适用于 SQLAlchemy 数据库会话 [英] Insert not working for SQLAlchemy database session

查看:52
本文介绍了插入不适用于 SQLAlchemy 数据库会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why isn't a record being inserted? There is an id returned but when I check the database there is no new record.

来自 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.

I've tried committing with transaction.commit() which doesn't get an error but doesn't insert a record. result.fetchone()[0] is getting an id.

DBSession.commit得到

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

推荐答案

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

This is because you are not using ORM to insert new rows threfore transaction doesn't know it should commit on it's own, because transaction state is not marked as dirty.

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

Place the following code after you DBSession.execute the query in your views.py.

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

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

At this point transaction should be able to properly commit your query, alternatively use ORM to insert the new row.

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

Here is a bit more on this subject:

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

默认情况下,zope.sqlalchemy 在第一次使用会话时将会话置于活动"状态.ORM 写操作会自动将会话移动到已更改"状态.这避免了不必要的数据库提交.有时需要直接通过SQL与数据库进行交互.无法猜测这样的操作是读还是写.因此,当手动 SQL 语句写入数据库时​​,我们必须手动将会话标记为已更改.

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.

这篇关于插入不适用于 SQLAlchemy 数据库会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆