0

I thought the code below automatically close a mysql connection after inserting a new row to the database, but when i checked the number of connection, it doesnt look like that it got closed. Not sure what's wrong with the code.

class dbq:

    def __init__(self):

        self._conn = mysql.connector.connect(user='XYZ', password='ZYX',
                                            host='000.111.222.333', database='users')

        self._cursor = self._conn.cursor()

    def closeConn(self):
        self._cursor.close()
        self._conn.close()

    def db_query(self, sql):
        self._cursor.execute(sql)
        rows = self._cursor.fetchall()

        df = DataFrame(rows, columns=self._cursor.column_names)
        return df

    def insert(self, sql, args):
        try:
            self._cursor.execute(sql, args)
            ''' printint is annoying
            if self._cursor.lastrowid:
                print('last insert id', self._cursor.lastrowid)
            else:
                print('last insert id not found')
            '''
            self._conn.commit()
        except Error as error:
            print(error)
        finally:
            self._cursor.close()
            self._conn.close()

def db_insert_master_text(phone, comments):
    sql = "INSERT INTO user_master_text_base(phone, comments, timestamp) VALUES(%s,%s,%s)"
    args = (phone, comments, datetime.datetime.now())
    db = dbq()
    db.insert(sql, args)

when I need to insert a new row, i just call:

db_insert_master_text('13473639718', 'Hi')

The number of connection after calling the function always increase although i have used .close() in defining the insert() function

llu13701
  • 133
  • 1
  • 12
  • Maybe you should also close it when the error occurs? – Michael Feb 11 '20 at 04:30
  • how do i close it automatically? – llu13701 Feb 11 '20 at 04:54
  • suggest using the `with` python syntax and use `__enter__` and `__exit__` hooks for initialization and closing connection [like this anwer](https://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object) – danblack Feb 11 '20 at 04:59

0 Answers0