gpt4 book ai didi

python - PyQt5 和使用 QtSql 的持久数据库

转载 作者:行者123 更新时间:2023-11-30 22:11:50 27 4
gpt4 key购买 nike

对 PyQt5 相当陌生,在设置示例应用程序时我遇到了 QtSql 的问题。我找到的所有示例都显示了使用数据库连接的单个类,但没有一个示例显示如何在需要数据库连接的许多不同类上持久使用 QtSql 类。我的应用程序中几乎所有 MDI 子窗口都需要连接到数据库,但是当我设置连接时,我收到连接“重复”的错误。我的问题是:

如果我有一个 MDI 应用程序,其中有多个需要数据库连接的对话框,如何持久设置数据库连接以便所有对话框都可以访问数据库?

最佳答案

如果您要连接到同一个数据库,则无需创建多个连接,只需创建一个连接,因为 qt 全局管理这些连接,如 docs 所示。 :

QSqlDatabase QSqlDatabase::addDatabase(const QString &type, constQString &connectionName = QLatin1String(defaultConnection))

Adds a database to the list of database connections using the driver type andthe connection name connectionName. If there already exists a databaseconnection called connectionName, that connection is removed.

The database connection is referred to by connectionName. The newlyadded database connection is returned.

If type is not available or could not be loaded, isValid() returnsfalse.

If connectionName is not specified, the new connection becomes thedefault connection for the application, and subsequent calls todatabase() without the connection name argument will return thedefault connection. If a connectionName is provided here, usedatabase(connectionName) to retrieve the connection.

Warning: If you add a connection with the same name as an existingconnection, the new connection replaces the old one. If you call thisfunction more than once without specifying connectionName, the defaultconnection will be the one replaced.


示例:

.
├── connection.py
├── main.py
└── views.p

连接.py

from PyQt5 import QtWidgets, QtSql


def createConnection():
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(":memory:")
if not db.open():
QtWidgets.QMessageBox.critical(None, "Cannot open database",
"Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit.", QtWidgets.QMessageBox.Cancel)
return False

query = QtSql.QSqlQuery()
query.exec_("""CREATE TABLE IF NOT EXISTS person (id int primary key,
firstname VARCHAR(20),
lastname VARCHAR(20))""")
query.exec_("insert into person values(101, 'Danny', 'Young')")
query.exec_("insert into person values(102, 'Christine', 'Holand')")
query.exec_("insert into person values(103, 'Lars', 'Gordon')")
query.exec_("insert into person values(104, 'Roberto', 'Robitaille')")
query.exec_("insert into person values(105, 'Maria', 'Papadopoulos')")


query.exec_("""CREATE TABLE IF NOT EXISTS items (id INT primary key,
imagefile INT,
itemtype varchar(20),
description varchar(100))""");
query.exec_("insert into items "
"values(0, 0, 'Qt',"
"'Qt is a full development framework with tools designed to "
"streamline the creation of stunning applications and "
"amazing user interfaces for desktop, embedded and mobile "
"platforms.')");
query.exec_("insert into items "
"values(1, 1, 'Qt Quick',"
"'Qt Quick is a collection of techniques designed to help "
"developers create intuitive, modern-looking, and fluid "
"user interfaces using a CSS & JavaScript like language.')");
query.exec_("insert into items "
"values(2, 2, 'Qt Creator',"
"'Qt Creator is a powerful cross-platform integrated "
"development environment (IDE), including UI design tools "
"and on-device debugging.')");
query.exec_("insert into items "
"values(3, 3, 'Qt Project',"
"'The Qt Project governs the open source development of Qt, "
"allowing anyone wanting to contribute to join the effort "
"through a meritocratic structure of approvers and "
"maintainers.')");
return True

views.py

from PyQt5 import QtWidgets, QtSql

class PersonWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(PersonWidget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
view = QtWidgets.QTableView()
lay.addWidget(view)
model = QtSql.QSqlTableModel(self)
model.setTable("person")
model.select()
view.setModel(model)

class ItemsWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ItemsWidget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
view = QtWidgets.QTableView()
lay.addWidget(view)
model = QtSql.QSqlTableModel(self)
model.setTable("items")
model.select()
view.setModel(model)

ma​​in.py

from PyQt5 import QtWidgets, QtSql

from connection import createConnection
from views import PersonWidget, ItemsWidget


class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)

self.mdiarea = QtWidgets.QMdiArea()
self.setCentralWidget(self.mdiarea)

sub1 = QtWidgets.QMdiSubWindow()
sub1.setWidget(PersonWidget())
self.mdiarea.addSubWindow(sub1)
sub1.show()

sub2 = QtWidgets.QMdiSubWindow()
sub2.setWidget(ItemsWidget())
self.mdiarea.addSubWindow(sub2)
sub2.show()

if __name__ == '__main__':
import sys

app = QtWidgets.QApplication(sys.argv)

if not createConnection():
sys.exit(-1)
w = MainWindow()
w.show()
sys.exit(app.exec_())

enter image description here

在前面的示例中,有 createConnection() 方法用于建立连接并在必要时创建表。而使用数据库数据而不指示连接的 View 因此使用默认连接,即在 createConnection() 中建立的连接。

关于python - PyQt5 和使用 QtSql 的持久数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51306683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com