Python Database connection Close

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

    You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

    import pyodbc
    
    class MS_DB():
        """ Collection of helper methods to query the MS SQL Server database.
        """
    
        def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
            self.username = username
            self._password = password
            self.host = host
            self.port = str(port)
            self.db = initial_db
            conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                        self.host + ';PORT='+ self.port +';DATABASE='+ \
                        self.db +';UID='+ self.username +';PWD='+ \ 
                        self._password +';'
            print('Connected to DB:', conn_str)
            self._connection = pyodbc.connect(conn_str)        
            pyodbc.pooling = False
    
        def __repr__(self):
            return f"MS-SQLServer('{self.username}', 

提交回复
热议问题