我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
我收到了很多错误的信息:
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"
作为Django项目的数据库引擎,从python-psycopg改为python-psycopg2。
代码保持不变,只是不知道这些错误来自哪里。
当前回答
作为对@priestc和@Sebastian的回应,如果你也这样做呢?
try:
conn.commit()
except:
pass
cursor.execute( sql )
try:
return cursor.fetchall()
except:
conn.commit()
return None
我刚刚尝试了这段代码,它似乎工作,失败无声,而不必关心任何可能的错误,并在查询良好时工作。
其他回答
我认为在使用PostgreSQL时,priestc提到的模式更有可能是这个问题的常见原因。
然而,我觉得这个模式有一些有效的用途,我不认为这个问题应该成为总是避免它的理由。例如:
try:
profile = user.get_profile()
except ObjectDoesNotExist:
profile = make_default_profile_for_user(user)
do_something_with_profile(profile)
如果你觉得这种模式没问题,但又不想到处都是显式的事务处理代码,那么你可能会考虑开启自动提交模式(PostgreSQL 8.2+): https://docs.djangoproject.com/en/dev/ref/databases/#autocommit-mode
DATABASES['default'] = {
#.. you usual options...
'OPTIONS': {
'autocommit': True,
}
}
我不确定是否有重要的性能考虑因素(或任何其他类型)。
我在postgres终端上运行故障事务时遇到了类似的行为。在此之后什么都没有通过,因为数据库处于错误状态。但是,作为一个快速解决方案,如果可以避免回滚事务。以下是我的诀窍:
提交;
这里也有类似的错误。我在这个链接https://www.postgresqltutorial.com/postgresql-python/transaction/中找到了答案
client = PsqlConnection(config)
connection = client.connection
cursor = client.cursor
try:
for query in list_of_querys:
#query format => "INSERT INTO <database.table> VALUES (<values>)"
cursor.execute(query)
connection.commit()
except BaseException as e:
connection.rollback()
这样,你发送给postgresql的以下查询将不会返回错误。
只需使用回滚
示例代码
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);")
我正在使用python包psycopg2,我在查询时得到了这个错误。 我一直只运行查询,然后运行execute函数,但是当我重新运行连接(如下所示)时,它解决了这个问题。所以重新运行什么是上面你的脚本即连接,因为有人说上面,我认为它失去了连接或不同步或其他。
connection = psycopg2.connect(user = "##",
password = "##",
host = "##",
port = "##",
database = "##")
cursor = connection.cursor()