Python Database connection Close

前端 未结 5 1035
一个人的身影
一个人的身影 2021-01-30 03:57

Using the code below leaves me with an open connection, how do I close?

import pyodbc
conn = pyodbc.connect(\'DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;D         


        
5条回答
  •  臣服心动
    2021-01-30 04:39

    You can wrap the whole connection in a context manager, like the following:

    from contextlib import contextmanager
    import pyodbc
    import sys
    
    @contextmanager
    def open_db_connection(connection_string, commit=False):
        connection = pyodbc.connect(connection_string)
        cursor = connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            error, = err.args
            sys.stderr.write(error.message)
            cursor.execute("ROLLBACK")
            raise err
        else:
            if commit:
                cursor.execute("COMMIT")
            else:
                cursor.execute("ROLLBACK")
        finally:
            connection.close()
    

    Then do something like this where ever you need a database connection:

    with open_db_connection("...") as cursor:
        # Your code here
    

    The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True).

提交回复
热议问题