Using a variable in a try,catch,finally statement without declaring it outside

前端 未结 2 594
执念已碎
执念已碎 2020-12-25 11:07

I\'m pretty new to Python, here is some code I am looking at:

try:
    connection = getConnection(database)
    cursor = connection.cursor()
    cursor.execu         


        
2条回答
  •  [愿得一人]
    2020-12-25 12:06

    I'd suggest using contexts, like:

    from contextlib import closing
    
    try:
        with closing(getConnection(database)) as connection:
            with closing(connection.cursor()) as cursor:
                cursor.execute("some query")
    except:
        log.error("Problem")
        raise
    

    This should ensure the closing (see more here). In some cases, you won't even need closing since connection is most likely to support the context protocol itself, so that would be just with getConnection(database)...

提交回复
热议问题