QT TableWidget更新MySQL表报错:'Ui_MainWindow'无connection属性
问题分析与解决
错误原因
你在update_table函数里创建了局部变量connection,但后续代码中却试图访问self.connection(实例属性),而你的Ui_MainWindow类从未定义过这个属性,因此触发AttributeError。
修复方案(两种可选)
方案一:直接使用局部变量
把代码里所有的self.connection替换成你已定义的局部变量connection,同时记得在操作完成后关闭连接避免资源泄漏:
def update_table(self): # Connect to the MySQL database connection = pymysql.connect( host='localhost', user='####', password='######', database='#####' ) table_data = [] table = self.tableWidget_4 try: # Execute the SQL update queries for each cell in the QTableWidget with connection.cursor() as cursor: for row in range(self.tableWidget_4.rowCount()): afm_item = self.tableWidget_4.item(row, 0) afm = afm_item.text() for column in range(1, self.tableWidget_4.columnCount()): item = self.tableWidget_4.item(row, column) value = item.text() column_name = self.tableWidget_4.horizontalHeaderItem(column).text() # Construct and execute the update query update_query = f"UPDATE pelates SET {column_name} = %s WHERE afm = %s" cursor.execute(update_query, (value, afm)) # Commit the changes to the database connection.commit() print("Table updated successfully!") except pymysql.Error as e: print(f"Error occurred while updating table: {e}") finally: # 关闭数据库连接 connection.close()
方案二:将连接设为实例属性
如果需要在多个函数里复用数据库连接,可以在窗口初始化时创建连接并设为实例属性,后续函数直接调用:
# 假设这是Ui_MainWindow的初始化方法 def __init__(self): super().__init__() # 初始化数据库连接为实例属性 self.connection = pymysql.connect( host='localhost', user='####', password='######', database='#####' ) # update_table函数直接使用self.connection def update_table(self): table_data = [] table = self.tableWidget_4 try: with self.connection.cursor() as cursor: for row in range(self.tableWidget_4.rowCount()): afm_item = self.tableWidget_4.item(row, 0) afm = afm_item.text() for column in range(1, self.tableWidget_4.columnCount()): item = self.tableWidget_4.item(row, column) value = item.text() column_name = self.tableWidget_4.horizontalHeaderItem(column).text() update_query = f"UPDATE pelates SET {column_name} = %s WHERE afm = %s" cursor.execute(update_query, (value, afm)) self.connection.commit() print("Table updated successfully!") except pymysql.Error as e: print(f"Error occurred while updating table: {e}")
额外提醒
- 方案一必须通过
finally块关闭连接,防止数据库连接资源泄漏。 - 你使用参数化查询(
%s占位符)避免SQL注入的做法是正确的,建议保持这个习惯。
内容的提问来源于stack exchange,提问作者FRANK F.
相关产品推荐
相关产品推荐

