在循环程序中解决“ ERROR 2006(HY000):MySQL服务器已消失”(mysql-connector-python)

问题描述 投票:0回答:1

我为最近遇到的类似问题提供了[[解决方案:

我有带有MySQL用户数据库的Telegram(信使)机器人。在代码开始处有与之的连接,导致连接在大约10个小时后消失。由于无法获取有关用户的信息,因此bot返回了错误。

我使用mysql-connector-python框架。解决方案是对数据库查询使用

class

。您可以在下面看到它以及使用示例。
python mysql mysql-connector mysql-connector-python mysql-error-2006
1个回答
0
投票

[班级:

import logging import mysql.connector class DB(): def __init__(self, **kwargs): self.conn = mysql.connector.connect( host="host", user="user", passwd="password", database="name" ) try: self.cursor = self.conn.cursor() except Exception as e: print(str(e)) def execute(self, query, data=None, ret1=False): try: if not self.conn: self.__init__() else: if data: self.cursor.execute(query, data) else: self.cursor.execute(query) if 'INSERT' in query or 'UPDATE' in query or 'DELETE' in query or 'DROP' in query: self.conn.commit() if ret1: return self.cursor.fetchone() else: return self.cursor.fetchall() except: logging.error('end', exc_info=True) return 'error'

表格示例

Table example

查询结构

res = DB().execute(query, protected data) # fetchall res = DB().execute(query, protected data, True) # fetchone

使用示例

> DB().execute("CREATE TABLE users (r_id INT AUTO_INCREMENT PRIMARY KEY, id INT UNIQUE, name VARCHAR(255), role INT NULL DEFAULT 3)") > DB().execute("INSERT INTO users (id, name, role) VALUES (%s, %s, %s)", (65453, "Mike", 1,)) > res = DB().execute(f"SELECT * FROM users") res = [(1, 146, "Nick", 3,), (2, 155, "John", 1,), (3, 678, "Michelle", 2,)] > res = DB().execute(f"SELECT * FROM users WHERE name = %s", ("John",), ret1=True) res = (2, 155, "John", 1,)
如果您有一些优化建议,请写下来!
© www.soinside.com 2019 - 2024. All rights reserved.