from PyQt5.QtWidgets import QApplication from PyQt5.uic import loadUi import pymysql class Stats: def init(self): # 从文件中加载UI定义 # 从 UI 定义中动态创建一个相应的窗口对象 # 注意:里面的控件对象也成为窗口对象的属性了 # 比如 self.ui.button , self.ui.textEdit self.ui = loadUi("Form - untitled.ui") # 信号和槽 self.ui.login.clicked.connect(self.handleCalc) def handleCalc(self): hostaddr = self.ui.hostaddr.text() username = self.ui.username.text() password = self.ui.password.text() database = self.ui.database.text() tablename = self.ui.tablename.text() con = connect(hostaddr,username,password,database,tablename) con.connect_to_database() # 连接数据库 # con = pymysql.connect(host=hostaddr, # user=username, # password=password, # database=database, # charset='utf8mb4', # ) # cur = con.cursor() # statement = "select * from {table} where id=1".format(table=tablename) # cur.execute(statement) # data = cur.fetchone() # print(data) # con.close() class connect: def init(self,hostaddr,username,password,database,tablename): self.hostaddr=hostaddr self.username=username self.password=password self.database=database self.tablename=tablename def connect_to_database(self): con = pymysql.connect(host=self.hostaddr, user=self.username, password=self.password, database=self.database, charset='utf8mb4', tablename=self.tablename, ) cur = con.cursor() statement = "select * from {table} where id=1".format(table=tablename) cur.execute(statement) data = cur.fetchone() print(data) con.close() if name == 'main': app = QApplication([]) stats = Stats() stats.ui.show() app.exec_()修改一下
时间: 2024-02-25 14:59:24 浏览: 119
PyQt5.QtWebEngine + JS 实现网页与Python的数据通信
5星 · 资源好评率100%
代码中的错误:
1. connect_to_database() 方法中,使用了变量 tablename,但是应该使用 self.tablename。
2. 在主函数的 if name == 'main' 中,没有加上模块名,应该是 if __name__ == '__main__'。
修改后的代码如下:
```
from PyQt5.QtWidgets import QApplication
from PyQt5.uic import loadUi
import pymysql
class Stats:
def __init__(self):
# 从文件中加载UI定义
# 从 UI 定义中动态创建一个相应的窗口对象
# 注意:里面的控件对象也成为窗口对象的属性了
# 比如 self.ui.button , self.ui.textEdit
self.ui = loadUi("Form - untitled.ui")
# 信号和槽
self.ui.login.clicked.connect(self.handleCalc)
def handleCalc(self):
hostaddr = self.ui.hostaddr.text()
username = self.ui.username.text()
password = self.ui.password.text()
database = self.ui.database.text()
tablename = self.ui.tablename.text()
con = connect(hostaddr,username,password,database,tablename)
con.connect_to_database()
class connect:
def __init__(self,hostaddr,username,password,database,tablename):
self.hostaddr=hostaddr
self.username=username
self.password=password
self.database=database
self.tablename=tablename
def connect_to_database(self):
con = pymysql.connect(host=self.hostaddr, user=self.username, password=self.password, database=self.database, charset='utf8mb4')
cur = con.cursor()
statement = "select * from {table} where id=1".format(table=self.tablename)
cur.execute(statement)
data = cur.fetchone()
print(data)
con.close()
if __name__ == '__main__':
app = QApplication([])
stats = Stats()
stats.ui.show()
app.exec_()
```
阅读全文