im用python编写代码,我需要用数据库select填充一个表,并且每5分钟刷新一次,有人能帮我吗?我已经尝试了很多方法,但都不对。
有什么建议吗?
MainWindow >
def createConnection():
connString = "host='*********' port='****' dbname='***' user='***' password='*******'"
global db
db = QSqlDatabase.addDatabase('QPSQL')
db.setDatabaseName(connString)
if db.open():
print('connect to SQL Server successfully')
return True
else:
print('connection failed')
return False
def displayData(sqlStatement):
print('processing query...')
qry = QSqlQuery(db)
qry.prepare(sqlStatement)
qry.exec()
model = QSqlQueryModel()
model.setQuery(qry)
view = QTableView()
view.setModel(model)
return view
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.showMaximized()
if createConnection():
SQL_STATEMENT = "select prod_descricao,prun_preco from produnidade inner join produtos ON (prod_codigo = prun_prod_codigo) where prun_unid_codigo = '101' limit 20"
dataView = displayData(SQL_STATEMENT)
dataView.show()
sys.exit(app.exec_())
您只需要执行一个QTimer即可再次设置查询:
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlQueryModel
def create_connection():
connString = (
"host='*********' port='****' dbname='***' user='***' password='*******'"
)
db = QSqlDatabase.addDatabase("QPSQL")
db.setDatabaseName(connString)
if db.open():
print("connect to SQL Server successfully")
return True
print("connection failed")
return False
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
if not create_connection():
sys.exit(-1)
model = QSqlQueryModel()
view = QTableView()
view.setModel(model)
def on_timeout():
SQL_STATEMENT = "SELECT prod_descricao, prun_preco FROM produnidade INNER JOIN produtos ON (prod_codigo = prun_prod_codigo) WHERE prun_unid_codigo = '101' LIMIT 20"
model.setQuery(SQL_STATEMENT)
QTimer.singleShot(5 * 1000, on_timeout)
on_timeout()
sys.exit(app.exec_())