开发CRUD时点击Insert按钮触发MySQL连接不可用错误求助
CRUD插入功能报错:MySQL连接不可用
我正在开发一个CRUD功能,点击Insert按钮时触发错误,每次尝试添加数据都会出现这个问题:
Traceback (most recent call last): File "C:\Users\mclov\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "C:\Users\mclov\pythonProject1\fluxo.py", line 53, in insertdata inserir(lista) File "C:\Users\mclov\pythonProject1\lira.py", line 14, in inserir cursor = conexao.cursor() File "C:\Users\mclov\abadabado\lib\site-packages\mysql\connector\connection_cext.py", line 706, in cursor raise OperationalError("MySQL Connection not available.") mysql.connector.errors.OperationalError: MySQL Connection not available.
相关代码片段:
def insertdata(): tempo = entry_tempo.get() evento = entry_descrição.get() debito = entry_entrada.get() credito = entry_saida.get() lista = [tempo, evento, debito, credito] if evento == '' or tempo == '' or credito=='' or debito=='': messagebox.showerror("campo não pode ser vazio") else: inserir(lista) messagebox.showinfo("todos os dados foram registrados") entry_tempo.delete(0, "end") entry_descrição.delete(0, "end") entry_entrada.delete(0, "end") entry_saida.delete(0, "end") for widget in frame_tabela.winfo_children(): widget.destroy() showitself()
解决方向
这个错误的核心是:调用conexao.cursor()时,数据库连接已经失效或未正确建立。
- 先检查
lira.py里的连接逻辑:- 是否在之前的操作后关闭了连接(比如调用过
conexao.close()) - 连接初始化后是否因超时、网络问题断开
- 是否在之前的操作后关闭了连接(比如调用过
- 最简单的修复方式:在
inserir函数内部每次重新建立连接,用完即关闭:def inserir(lista): # 替换为你的数据库配置 conexao = mysql.connector.connect( host="localhost", user="你的用户名", password="你的密码", database="目标数据库名" ) cursor = conexao.cursor() # 执行插入SQL语句 sql = "INSERT INTO 表名 (tempo, evento, debito, credito) VALUES (%s, %s, %s, %s)" cursor.execute(sql, lista) conexao.commit() # 关闭资源 cursor.close() conexao.close() - 如果想复用连接,就在获取游标前检查连接状态,断开则重连:
def inserir(lista): if not conexao.is_connected(): conexao.reconnect() cursor = conexao.cursor() # 后续插入逻辑...
内容的提问来源于stack exchange,提问作者jeffte lucas
相关产品推荐
相关产品推荐

