回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在创建一个简单的桌面应用程序,它将用户连接到数据库,并允许他执行一些简单的操作(如添加一些数据等)</p>
<p>我还需要创建一个窗口来显示数据库中的行数。下面的函数返回行数</p>
<pre><code>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))
</code></pre>
<p>现在我想在一个窗口中打印这个结果(下面的代码非常简单)</p>
<pre><code>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_())
</code></pre>
<p>第一次“咔嗒”就完美地工作了。不幸的是,在向我的数据库添加了一些东西(使用应用程序或MYSQLWorkbench)并再次调用该函数之后,行号不会刷新。你知道吗</p>
<p>我真的很想知道我的逻辑和代码有什么问题。我将感谢任何帮助。你知道吗</p>
<p>编辑。<br/>
我尝试了以下代码,我认为RowCounter函数有问题。你知道吗</p>
<pre><code>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(), '.')
</code></pre>
<p>AddRecord函数起作用。这是我数据库中的最新记录。
<a href="https://i.stack.imgur.com/jxgyu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jxgyu.png" alt="Last row in a database"/></a></p>
<p>这就是终端的输出
<a href="https://i.stack.imgur.com/9UDU5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9UDU5.png" alt="Output"/></a></p>