【问题标题】:SQL Alchemy - Transaction isn't workingSQL Alchemy - 事务不工作
【发布时间】:2016-03-15 18:43:30
【问题描述】:

我使用的是 SQL Alchemy 核心版本 1.1,但我似乎无法在我的 falcon (python) 应用程序中进行事务处理。据我所知,我正确地遵循了文档。

编辑:数据库 postgresql -> psycopg2cffi

def __init__(self, *args, **kwargs):
    self.__conn_url__ = settings.get_db_url()
    self.db_engine = create_engine(self.__conn_url__)
    self.db_engine.echo = False
    self.metadata = MetaData(self.db_engine)
    self.connection = self.db_engine.connect()
    self.organization_types_table = Table('organization_types', self.metadata, autoload=True)
    self.organization_type_names_table = Table('organization_type_names', self.metadata, autoload=True)

def post(self, json_data):
    transaction = self.connection.begin()
    print(transaction)
    try:
        results = self.organization_types_table.insert().\
            values(date_created=datetime.datetime.now()).\
            execute()

        organization_types_id = results.inserted_primary_key

        results = self.organization_type_names_table.insert().\
            values(organization_types_id=organization_types_id[0],
                   lang=json_data['lang'],
                   name=json_data['name']).\
            execute()

        transaction.commit()
        print("I didn't rollback")
        return results
    except:
        transaction.rollback()
        print("I rollback :D")
        raise

如果我多次运行此代码并插入相同的对象。由于索引约束不允许重复,它应该只在第一次工作。

我会根据我的 print() 语句得到的结果:

  1. 事务对象 -> 我没有回滚
  2. 事务对象 -> 我回滚 :D
  3. 事务对象 -> 我回滚 :D

如果我查看表内部,我可以清楚地看到 organization_types_table 包含 3 条记录,而 organization_type_names 包含 1 条记录。为什么 organization_types_table 不根据事务回滚?

【问题讨论】:

  • 您使用的是什么数据库?它的默认隔离级别是多少?例如 MySQL 上的 MyISAM 默认工作在自动提交模式,这意味着没有事务。
  • @univerio postgresql -> psycopg2cffi
  • 我认为你需要做self.connection.execute(query)而不是query.execute(),后者相当于self.db_engine.execute(query),反过来,它会获取一个新的连接,而不是使用那个您有一笔交易未结。
  • @univerio 成功了!您要发布答案以获得功劳吗?

标签: python sqlalchemy spring-transactions falcon


【解决方案1】:

你需要做的

self.connection.execute(query)

而不是

query.execute()

query.execute() 在引擎上执行query,它会获取一个新连接,而不是使用您打开了事务的那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2016-04-13
    • 1970-01-01
    • 2012-04-21
    • 2016-09-30
    相关资源
    最近更新 更多