【发布时间】:2013-02-04 17:56:36
【问题描述】:
我正在使用 MySQLdb 使用 python 连接到 MySQL。我的表都是 InnoDB,我正在使用事务。
我正在努力想出一种跨职能“共享”交易的方法。考虑以下伪代码:
def foo():
db = connect()
cur = db.cursor()
try:
cur.execute(...)
conn.commit()
except:
conn.rollback()
def bar():
db = connect()
cur = db.cursor()
try:
cur.execute(...)
foo() # note this call
conn.commit()
except:
conn.rollback()
在我的代码中的某些时候,我需要调用foo(),在某些时候我需要调用bar()。这里的最佳做法是什么?如果在bar() 外部而不是bar() 内部调用,我将如何告诉foo() 到commit() 的调用?如果有多个线程调用foo() 和bar() 并且对connect() 的调用不返回相同的连接对象,这显然会更复杂。
更新
我找到了适合我的解决方案。我已经包装了connect(),以便在调用时增加一个值。调用 commit() 会减少该值。如果调用commit() 并且该计数器的> 0,则不会发生提交并且值会递减。因此,您会得到:
def foo():
db = connect() # internal counter = 1
...
db.commit() # internal counter = 0, so commit
def bar():
db = connect() # internal counter = 1
...
foo() # internal counter goes to 2, then to 1 when commit() is called, so no commit happens
db.commit() # internal counter = 0, so commit
【问题讨论】:
-
尝试扩展 MySQLdb 并走单例/工厂路线(这是我们在我的项目中所做的)
标签: python mysql mysql-python