Python Database connection Close

前端 未结 5 936
一个人的身影
一个人的身影 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:42

    Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

    import pyodbc
    conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
    
    csr = conn.cursor()  
    csr.close()
    conn.close()     #<--- Close the connection
    

    Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

    import pyodbc
    conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
    with conn:
        crs = conn.cursor()
        do_stuff
        # conn.commit() will automatically be called when Python leaves the outer `with` statement
        # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!! 
    

    See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.

    Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.


    Also note that regardless of whether or not you use the with statements, per the docs,

    Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

    and similarly for cursors (my emphasis):

    Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

提交回复
热议问题