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