我收到了很多错误的信息:

"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"

作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。

代码保持不变,只是不知道这些错误来自哪里。


当前回答

只需使用回滚

示例代码

try:
    cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")
except:
    cur.execute("rollback")
    cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")

其他回答

只需使用回滚

示例代码

try:
    cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")
except:
    cur.execute("rollback")
    cur.execute("CREATE TABLE IF NOT EXISTS test2 (id serial, qa text);")

这是一个糟糕的sql执行问题,它不允许其他查询执行,直到前一个查询被挂起/回滚。

在PgAdmin4-4.24中有一个回滚选项,可以尝试一下。

我也遇到了类似的问题。解决方案是迁移db (manage.py syncdb或manage.py schemmigration——auto <表名>如果您使用south)。

当查询产生错误,而您试图在不先回滚事务的情况下运行另一个查询时,postgres就会这样做。(你可能会认为这是一个安全功能,防止你破坏你的数据。)

要解决这个问题,您需要找出在代码中执行错误查询的位置。在postgresql服务器中使用log_statement和log_min_error_statement选项可能会有所帮助。

根据我的经验,这些错误是这样发生的:

try:
    code_that_executes_bad_query()
    # transaction on DB is now bad
except:
    pass

# transaction on db is still bad
code_that_executes_working_query() # raises transaction error

第二个查询没有问题,但是由于捕获了真正的错误,第二个查询将引发(信息量少得多的)错误。

edit:这只发生在except子句捕捉到IntegrityError(或任何其他低级数据库异常)时,如果你捕捉到像DoesNotExist这样的错误,这个错误将不会出现,因为DoesNotExist不会破坏事务。

这里的教训是不要尝试/except/pass。