Python类操作MySQL报错:'MySQLConnection'对象无'execute'属性
MySQLConnection无execute属性错误分析与修复
问题场景
使用Python操作本地MySQL服务器,单独编写读写方法时可正常运行,但将方法封装到DatabaseOperations类后,调用readFromDatabase和writeToDatabase方法出现如下错误:
AttributeError: 'MySQLConnection' object has no attribute 'execute'
类实现代码如下:
# DATABASE STUFF class DatabaseOperations: def __init__(self): self.local_ip = '192.168.105.181' # LOCAL MACHINE SERVER RUNNING ON self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCK_DGRAM refers to UDP self.s.connect((self.local_ip, 80)) self.db_connection = mysql.connector.connect( host="localhost", user="myuser", password="12345", database="Testing" ) def readFromDatabase(self): db_cursor = self.db_connection db_cursor.execute( f"select * from receiving;" ) db_result = db_cursor.fetchall() print(db_result) def writeToDatabase(self): db_cursor = self.db_connection # Loop through ResultsLists and print value at given index position for i in range(len(globalResultsList)): print(f'RESULTS FROM LOOP: {globalResultsList[i]}') # If the next iterator is larger than the length of the list => break out of loop if i+1 >= len(globalResultsList): return db_cursor.execute( f"INSERT INTO receiving (client_ip, client_message) VALUES( '{globalClient}', '{globalResultsList[0]}');" ) self.db_connection.commit() db_cursor.close()
错误原因
核心问题是把数据库连接对象(MySQLConnection)当成了游标对象(Cursor)使用:
- 单独写方法时,你应该是先通过连接创建游标(
cursor = connection.cursor()),再用游标执行SQL; - 但类实现中,你直接将
self.db_connection赋值给db_cursor,而MySQLConnection对象本身没有execute方法——这个方法是游标对象的专属方法。
修复方案
修改两个读写方法,先通过数据库连接创建游标,再用游标执行SQL:
修复后的readFromDatabase方法
def readFromDatabase(self): db_cursor = self.db_connection.cursor() # 创建游标对象 db_cursor.execute("select * from receiving;") db_result = db_cursor.fetchall() print(db_result) db_cursor.close() # 用完关闭游标释放资源
修复后的writeToDatabase方法
def writeToDatabase(self): db_cursor = self.db_connection.cursor() # 创建游标对象 for i in range(len(globalResultsList)): print(f'RESULTS FROM LOOP: {globalResultsList[i]}') if i+1 >= len(globalResultsList): return # 改用参数化查询,避免SQL注入风险 db_cursor.execute( "INSERT INTO receiving (client_ip, client_message) VALUES(%s, %s);", (globalClient, globalResultsList[0]) ) self.db_connection.commit() db_cursor.close()
额外注意事项
- 禁止用f-string拼接SQL:这会引发严重的SQL注入漏洞,必须使用参数化查询(如上述代码中的
%s占位符); - 类中初始化的socket连接与数据库操作无关,建议移除,避免不必要的资源占用;
- 可在类的
__del__方法中添加数据库连接关闭逻辑,或使用上下文管理器(with语句)管理连接和游标,确保资源正常释放。
内容的提问来源于stack exchange,提问作者user8901723980173
相关产品推荐
相关产品推荐

