尝试异常处理

时间:2015-01-08 15:28:30

标签: python postgresql python-2.7

我正在尝试在Python 2.7中插入update语句。我正在使用Try和Except,但我认为有时候除外也可能会失败。有没有办法捕获此错误?

我的意思如下:

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

似乎这是没有真正记录的内容。顺便说一下,使用Postgres并找不到合适的UPSERT,这在StackO的某处提出。

4 个答案:

答案 0 :(得分:3)

您可以嵌套try-except clauses

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

注意:您应该在except子句中指定例外类型:

except InsertException: # or the one that fits better

编辑:如果插入失败,更新将失败,那么将更新语句放在第一个except中是没有意义的。

答案 1 :(得分:1)

通常,在您的except块中有另一个try块:

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


这是一个完整的示例,用于说明此建议的try / except方法的问题:

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

答案 2 :(得分:0)

如果发生这种情况,你真正需要做的就是:

try:
    execute insert statement [example]
except: 

    try:
        execute update statement [example]
    except: 

它可以按照您的预期运作。

答案 3 :(得分:-1)

您可以嵌套try / except:

>>> 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
相关问题