无法关闭与python的mysql连接
我认为下面的代码在向数据库插入新行后会自动关闭mysql连接,但当我检查连接数时,它看起来并没有关闭。不确定代码出了什么问题无法关闭与python的mysql连接,mysql,python-3.x,Mysql,Python 3.x,我认为下面的代码在向数据库插入新行后会自动关闭mysql连接,但当我检查连接数时,它看起来并没有关闭。不确定代码出了什么问题 class dbq: def __init__(self): self._conn = mysql.connector.connect(user='XYZ', password='ZYX', host='000.111.222.333', database=
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)
当我需要插入新行时,我只需调用:
db_insert_master_text('13473639718', 'Hi')
尽管我在定义insert()时使用了.close(),但调用函数后的连接数始终在增加函数当错误发生时,您可能也应该关闭它?如何自动关闭它?建议使用
和python语法,并使用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu