You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pymysql创建账号报错:Connection对象无execute属性求助

解决Connection' object has no attribute 'execute'报错

问题根源

你犯了个基础错误:pymysql里执行SQL的是游标对象(cursor),不是连接对象(Connection)。con是连接实例,它负责和数据库建立连接,而execute()是游标cur的方法,调用con.execute()才会触发这个报错。

另外代码里还有两个小bug:

  • con.comit()拼写错误,正确写法是con.commit()
  • con.close没加括号,不会真正关闭连接,要写成con.close()

修正后的代码

from tkinter import *
from tkinter import ttk, messagebox
from tkcalendar import *
import pymysql
import pymysql.cursors
import os

# 账号创建相关代码修正
con = pymysql.connect(host="localhost", port=3306, user="root", password="", database="database")
cur = con.cursor()
# 改用游标cur执行SQL语句
cur.execute("select * from compte where var=%s", self.var.get())
row = cur.fetchone()

con.commit()  # 修正拼写错误
con.close()   # 加括号调用关闭方法

额外优化建议

如果是创建账号(插入数据),执行完INSERT语句后必须调用commit()提交事务;如果只是查询,commit()可以省略。

推荐用with语句管理连接和游标,无需手动关闭,会自动释放资源,代码更健壮:

with pymysql.connect(host="localhost", port=3306, user="root", password="", database="database") as con:
    with con.cursor() as cur:
        # 示例:插入账号的SQL操作
        # cur.execute("INSERT INTO compte (var, ...) VALUES (%s, ...)", (self.var.get(), ...))
        cur.execute("select * from compte where var=%s", self.var.get())
        row = cur.fetchone()
    con.commit()

内容的提问来源于stack exchange,提问作者Roy The Producer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:55:17