使用 PyQt4 处理 mysql

Handling mysql using PyQt4

所以,我有一个 mysql 数据库患者,其中有一个客户端 table。我需要在 table 中的 GUI window 中显示有关客户端的信息。我还需要按主要字段进行筛选以获取更详细的信息(分别是姓氏、姓名、一系列文件、一系列政策等),并有可能同时在多个字段中进行搜索。我从下面的代码开始。 第一个问题是:在这个任务中什么容易使用 - QSqlTableModel 还是只是 QTableWidget? 问题 2 是:如何按主要字段筛选?那是什么意思? 如果有任何关于这个主题的想法,我将非常高兴。

from PyQt4.QtGui import *
from PyQt4.QtSql import *
import sys

def main_():
    app     = QApplication(sys.argv)
    table   = QTableWidget()
    db      = QSqlDatabase.addDatabase("QMYSQL")


    db.setHostName("127.0.0.1")
    db.setDatabaseName("patients")
    db.setUserName("root")
    db.setPassword("")
    table_name = "client"

    if (db.open()==False):
      QMessageBox.critical(None, "Database Error",
                db.lastError().text())

    query = QSqlQuery ("select * from "+ table_name + " limit 10")

    table.setColumnCount(query.record().count())
    table.setRowCount(query.size())

    index=0
    while (query.next()):
        table.setItem(index,0,QTableWidgetItem(query.value(0).toString()))
        table.setItem(index,1,QTableWidgetItem(query.value(1).toString()))
        index += 1
    table.show()
    return app.exec_()

if __name__ == '__main__':
    main_()

我想你想阅读更多关于模型-视图概念的内容。

打开数据库连接后,创建数据模型,然后将其附加到视图...无需迭代:

model = QtSql.QSqlTableModel()
# selecting a table
model.setTable("clients")
# applying a filter
model.setFilter("id > 0")
# i.e.: executing the query
model.select()

# the widget to show the data
tableView = QTableView()
# attach the model to widget
tableView.setModel(model)


tableView.show()

另外:如果您无法打开数据库 - 退出程序,不仅会出现一个消息框。

希望对您有所帮助。