2015-01-08 379 views
0

我想在Python 2.7中插入更新語句。我使用Try和Except,但認爲有時除了可能會失敗。有沒有辦法捕捉到這個錯誤?嘗試異常處理

我的意思是這樣的:

try: 
    execute insert statement [example] 
except: 
    execute update statement [example] 
    WHAT IF THIS FAILS? (This is my question) 

看來,這是一件是不是真的記錄。順便說一句,使用Postgres並找不到合適的UPSERT,並在StackO上的某個位置提出這個建議。

+0

您可以在另一個除外塊中嵌套另一個try-except塊 –

+1

請注意,Python異常處理未同步到事務狀態。當你捕獲一個Python異常時,你的事務仍然處於無效狀態,並且不會成功運行新的語句。你必須在你的try塊旁邊使用保存點。 –

回答

3

可以嵌套try-except clauses

try: 
    execute insert statement [example] 
except: 
    try: 
     execute update statement [example] 
    except: 
     handle the errors 

注:你應該E指定except子句中的異常類型:

except InsertException: # or the one that fits better 

編輯:如果更新會失敗,如果插入失敗,那麼將更新語句放在第一個except中是沒有意義的。

+1

這樣做的問題是,如果插入語句失敗,則更新語句也將失敗,因爲事務將不再有效。 – Bruno

+0

有輸入第二個除外的地方。你必須把相應的代碼放在那裏。 – Christian

+0

我的意思是,在這種特定情況下,更新將總是失敗,'psycopg2.InternalError:當前事務中止,命令被忽略直到事務塊結束(請參閱我的答案)。 – Bruno

-1

可以通過嵌套的try /除外:

>>> try: 
... 1/0 
... except: 
... print "in except" 
... try: 
...  "1"+[1] 
... except: 
...  print "second one" 
... 
in except 
second one 

你的情況:

try: 
    execute insert statement [example] 
except: 
    #insert failed 
    try: 
     execute update statement [example] 
    except: 
     #update failed 
0

如果出現這種情況,你真正需要做的是這樣的:

try: 
    execute insert statement [example] 
except: 

    try: 
     execute update statement [example] 
    except: 

它按照您的預期工作。

+0

感謝Eithos,肯定會給這個嘗試。似乎@bruno試圖說明,當插入和插入失敗時,事務將失敗。這是在大多數情況下(我們的情況)與數據庫或其他東西的錯誤。所以這需要在嵌套的except子句中捕獲(以便我們捕獲所有錯誤)。感謝大家的快速回復。任何人都討厭Postgres在2015年沒有原生Upsert的事實? – user2164689

1

在一般情況下,有你在另一個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