我正在创建一个简单的桌面应用程序,它将用户连接到数据库,并允许他执行一些简单的操作(如添加一些数据等)
我还需要创建一个窗口来显示数据库中的行数。下面的函数返回行数
import mysql.connector
mydb = mysql.connector.connect(
host = 'localhost',
user = 'root',
passwd = 'some_password',
database = 'some_database'
)
mycursor = mydb.cursor()
def RowCounter():
query = 'SELECT * FROM `some_database`'
mycursor.execute(query)
x = mycursor.fetchall()
return(len(x))
现在我想在一个窗口中打印这个结果(下面的代码非常简单)
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import *
from RowCounter import RowCounter
class TestWindow(QMainWindow):
def __init__(self):
super().__init__()
self.title='Row counter'
self.left=10
self.top=10
self.width=640
self.height=480
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left,self.top,self.width,self.height)
self.qlabel = QLabel(self)
self.qlabel.move(10, 100)
self.qlabel.resize(210, 32)
self.qlabel.setText('Number of rows in your database:')
self.textbox = QLineEdit(self)
self.textbox.resize(30, 32)
self.textbox.move(250, 100)
self.textbox.setReadOnly(True)
self.textbox.setVisible(False)
self.button_refresh = QPushButton('Refresh', self)
self.button_refresh.clicked.connect(self.on_call)
self.button_refresh.resize(200,32)
self.button_refresh.move(210,425)
self.show()
def on_call(self):
self.textbox.setText('')
self.textbox.setVisible(True)
x = RowCounter()
self.textbox.setText(str(x))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = TestWindow()
sys.exit(app.exec_())
第一次“咔嗒”就完美地工作了。不幸的是,在向我的数据库添加了一些东西(使用应用程序或MYSQLWorkbench)并再次调用该函数之后,行号不会刷新。你知道吗
我真的很想知道我的逻辑和代码有什么问题。我将感谢任何帮助。你知道吗
编辑。
我尝试了以下代码,我认为RowCounter函数有问题。你知道吗
import mysql.connector
from AddRecord import AddRecord
mydb = mysql.connector.connect(
host = 'localhost',
user = 'root',
passwd = 'some_password',
database = 'some_database'
)
def RowCounter():
mycursor_1 = mydb.cursor()
query = 'SELECT COUNT(*) FROM `pocztowki`'
mycursor_1.execute(query)
x = mycursor_1.fetchone()
mycursor_1.close()
return(x[0])
print('The amount of rows: ', RowCounter(), '.')
AddRecord(name='Alice', surname='Cooper', other=1, title='Guitar')
print('Everything is O.K.')
print('The amount of rows after calling the function "AddRecord": ', RowCounter(), '.')
尝试在函数中打开和关闭光标。你知道吗
还要确保无论在何处插入新数据,都会提交更新。你知道吗
我遇到了完全相同的问题,但正在将所有信息加载到QTableWidget上 因此,我使用以下代码获取所有行(根据您的需要进行修改)
相关问题 更多 >
编程相关推荐