-1

我在 python 中编写代码,我需要用数据库选择来填写一个表,并且每 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_())
4

1 回答 1

0

你只需要做一个 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_())
于 2020-03-26T21:45:55.283 回答