我正在使用Python中的Psycopg2访问PostgreSQL数据库.我很好奇,使用with closing()
模式来创建和使用游标是否安全,或者是否应该使用围绕查询的显式try/except
.我的问题是关于插入或更新,以及事务.
据我所知,所有Psycopg2查询都发生在一个事务中,这取决于调用代码来提交或回滚事务.如果with closing(...
块内发生错误,是否发出回滚?在较旧版本的Psycopg2中,在close()
上明确发布了回滚,但现在不再是这种情况(参见http://initd.org/psycopg/docs/connection.html#connection.close).
举个例子,我的问题可能更有意义.下面是一个使用with closing(...
的例子
with closing(db.cursor()) as cursor:
cursor.execute("""UPDATE users
SET password = %s, salt = %s
WHERE user_id = %s""",
(pw_tuple[0], pw_tuple[1], user_id))
module.rase_unexpected_error()
cursor.commit()
当模块启动时会发生什么.raise_unexpected_error()引发错误?交易是否回滚?据我所知,我要么提交它们,要么回滚它们.那么在这种情况下,会发生什么?
或者,我可以这样写我的查询:
cursor = None
try:
cursor = db.cursor()
cursor.execute("""UPDATE users
SET password = %s, salt = %s
WHERE user_id = %s""",
(pw_tuple[0], pw_tuple[1], user_id))
module.rase_unexpected_error()
cursor.commit()
except BaseException:
if cursor is not None:
cursor.rollback()
finally:
if cursor is not None:
cursor.close()
我还应该提到,我不知道Psycopg2的connection class cursor()
方法是否会引发错误(文档中没有说明),所以安全性比抱歉要好,不是吗?
我应该使用哪种发出查询和管理事务的方法?