关闭游标和异常

huangapple go评论68阅读模式
英文:

Closing cursors and exception

问题

在处理SQL游标中的异常时,关闭游标和数据库是一种正确的做法。以下是一种处理异常的方法:

try:
    my_cursor = my_database.cursor(buffered=True)
    my_sql_query = "SELECT MY_FIELDS FROM MY_TABLE"
    my_cursor.execute(my_sql_query)
    my_selected_rows = my_cursor.fetchall()

    for rows in my_selected_rows:
        # 进行一些操作
    my_cursor.close()
    my_database.close()

except Exception as e:
    if my_cursor is not None:
        my_cursor.close()
    if my_database is not None:
        my_database.close()

在PyCharm中,您提到的警告 "Local variable might be referenced before assignment" 是因为IDE检测到在异常处理块之外引用了my_cursormy_database,即使它们在异常情况下可能未分配值。为了解决这个警告,您可以在try块之前初始化这些变量,例如:

my_cursor = None
my_database = None

try:
    my_cursor = my_database.cursor(buffered=True)
    my_sql_query = "SELECT MY_FIELDS FROM MY_TABLE"
    my_cursor.execute(my_sql_query)
    my_selected_rows = my_cursor.fetchall()

    for rows in my_selected_rows:
        # 进行一些操作
    my_cursor.close()
    my_database.close()

except Exception as e:
    if my_cursor is not None:
        my_cursor.close()
    if my_database is not None:
        my_database.close()

这样可以避免警告,并且在异常情况下也能够正常关闭游标和数据库连接。

英文:

What is the "correct" way to deal with exceptions in a code block using a SQL cursor ?
Is it necessary/recommended to close the cursor and the database? If so, what is the correct way to do it?

I use to do it like this:

    try:
        my_cursor = my_database.cursor(buffered=True)
        my_sql_query = "SELECT MY_FIELDS FROM MY_TABLE"
        my_cursor.execute(my_sql_query )
        my_selected_rows = my_cursor.fetchall()
        
        for rows in my_selected_rows :
            do_something
        my_cursor.close()
        my_database.close()
        
    except Exception as e:        
        if my_cursor is not None:
            my_cursor.close()
        if my_database is not None:
            my_database.close()

In PyCharm, this code rise two warnings "Local variable might be referenced before assignment" for the line if my_cursor is not None and if my_database is not None

答案1

得分: 1

一种解决方法是使用contextlib.ExitStack

from contextlib import ExitStack

with ExitStack() as stack:
    my_database = connect(...)
    stack.callback(my_database.close)
    my_cursor = my_database.cursor(buffered=True)
    stack.callback(my_cursor.close)
    .
    .
    .

一旦退出 with无论是正常退出还是由于异常),如果数据库连接或游标的创建没有引发异常将调用`close`方法
英文:

One way to solve this is the use of contextlib.ExitStack:

from contextlib import ExitStack

with ExitStack() as stack:
    my_database = connect(...)
    stack.callback(my_database.close)
    my_cursor = my_database.cursor(buffered=True)
    stack.callback(my_cursor.close)
    .
    .
    .

As soon as the with-block is left (regardless if regularly or by exception) the close methods are called if the creation of db connection or cursor didn't raise an exception themselves.

答案2

得分: 0

我认为你非常接近了。但是我认为在创建数据库或游标时不应该期望引发异常,所以它们应该在try - except之前创建。这样你就不会收到你提到的警告。
回到第一个问题:最安全的方法是在不再需要它们之后始终关闭游标和连接。

英文:

I think you're very close. However I assume that you should not expect Exception to be raised while creating database or a cursor, so those should be created before try - except. This way you won't get warnings that you've mentioned.
Back to the first question: the most secure approach is to always close both - cursor and connection - after you don't need them anymore.

huangapple
  • 本文由 发表于 2023年3月7日 18:36:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定