【问题标题】:SQLAlchemy (no ORM): update statement not committingSQLAlchemy(无 ORM):更新语句未提交
【发布时间】:2012-10-22 22:20:06
【问题描述】:

我的数据库模块中有这个(匿名)函数:

def fix_publishing_dates(row_id, last_time=None, next_time=None,
    next_index=1, user="python_script"):
  sql = """
  UPDATE
    schema.table
  SET
    last_time = :last_time
  , next_time = :next_time
  , next_index = :next_index
  , col4 = SYSDATE
  , col5 = :user_id
  , is_active = 1
  WHERE
    id = :row_id
  """
  with closing(Session()) as s:
    with s.begin_nested():
      user_id = get_userid_by_name(user)
      args = dict(
          last_time=last_time,
          next_time=next_time,
          next_index=next_index,
          row_id=row_id,
          user_id=user_id,
          )
      s.execute(sql, args)
      s.flush()
    s.commit()

由于某种原因,这不起作用。我在上表中查询 is_active=1,得到零行。我在这里做错了什么吗?

注意

我不想使用 SQLAlchemy ORM 并为此添加大量样板表类*;我只是喜欢使用带有文本查询的 Session() 来支持事务。

*:内省也不会减慢我的启动时间;到这个数据库的网络管道很慢。

编辑 1

  • 我正在通过 cx_oracle 使用 Oracle 11 数据库。
  • 如果重要的话,其中一个绑定值有时是 None/
  • 此代码(以不同方式匿名)也不起作用:

    def fix_publishing_dates(**kwargs):
      sql = insert_query_here
      user_id = get_userid_by_name(user)
      args = dict(kwargs)
      print "*" * 50
      print "* About to update database with values: {}".format(args)
      print "*" * 50
      result = engine.execute(sql, args)
      print "Row count is:", result.rowcount
      #import ipdb;ipdb.set_trace()
      #s.commit()
    

【问题讨论】:

  • 您使用的是哪个数据库和哪个版本?其中一些不允许嵌套事务。
  • 使用 create_engine() 打开 echo=True 以查看您期望的 SQL 是否已发出,您还可以获得 s.execute() 的结果并看到 result.rowcount 不为零。 flush() 也完全是多余的(就像 begin_nested() 一样,真的,但也许你在 IRL 上有更复杂的事情)
  • 我目前只有一个真正需要事务的函数。那是所有的 INSERT 语句,它与原始 SQL 和 Session() 一起工作得很好。

标签: python sql sqlalchemy


【解决方案1】:

我认为 Sessions 不会在不使用 ORM 对象的情况下管理事务。但是你可以直接使用引擎上的事务:

with engine.begin() as conn:
    conn.execute(...)

【讨论】:

  • 好吧,Session确实做一个事务,但是如果你只是发出原始 SQL,那么没有太多理由使用 Session。 flush() 也是不必要的。我不确定为什么 UPDATE 最初会失败,但是 with begin_nested() 应该提交内部 trans。
  • 我知道冲洗应该是不必要的,但我越来越绝望了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2013-03-06
  • 2019-05-12
相关资源
最近更新 更多