在一般情況下,有你在另一個try塊except塊:
try:
Attempt something here.
except:
try:
Attempt something else here.
except:
Handle the problem here.
然而,這可能不會解決您的示例問題:
try:
execute insert statement [example]
except:
execute update statement [example]
未能插入第一意願肯定使您的交易無效(假設您正在使用交易):在這種情況下,更新聲明也會失敗。 (如果你沒有使用事務處理,無論如何,這兩個語句都可能失敗。)
你可以改爲查看PostgreSQL中UPDATE/INSERT的其他策略,例如this question。
下面是說明這一問題的一個完整的示例建議嘗試/除的方法來UPSERT:
import psycopg2
conn = psycopg2.connect(database='test_so27843654')
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS test_table")
cursor.execute(""" CREATE TABLE test_table (
id INTEGER PRIMARY KEY,
val TEXT
) """)
cursor.execute("INSERT INTO test_table (id, val) VALUES (1, 'Test 1')")
try:
cursor.execute("""
INSERT INTO test_table (id, val) VALUES (1, 'Other Test 1')
""")
print "Inserted..."
except:
try:
cursor.execute("""
UPDATE test_table SET val='Other Test 1' WHERE id=1
""")
print "Updated..."
except:
raise
conn.commit()
這將始終失敗:psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block
。
您可以在另一個除外塊中嵌套另一個try-except塊 –
請注意,Python異常處理未同步到事務狀態。當你捕獲一個Python異常時,你的事務仍然處於無效狀態,並且不會成功運行新的語句。你必須在你的try塊旁邊使用保存點。 –