PyQt 子类化 QSqlDatabase 来制造异常。

问题描述 投票:0回答:1

我喜欢从QSqlDatabase和QSqlQuery以及各种模型中获得的所有好处。但我真的希望当发生错误时能抛出异常。所以我想也许我可以子类化QSqlDatabase,当open()方法失败时抛出一个异常。

from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableView)
from PyQt5.QtSql import (QSqlQuery, QSqlQueryModel, QSqlDatabase)
import sys

class ExceptionalDatabase(QSqlDatabase):

    #def addDatabase(self, *args, **kwargs):
        # what to put here? I need to return an instance of
        # ExceptionalDatabase, right?
        #
        # this doesn't work:
        # return super(ExceptionalDatabase, self).addDatabase(*args, **kwargs)

    def open(self, user=None, pwd=None):
        # this method will never be called, because addDatabase will
        # return a QSqlDatabase instance
        if user is None:
            retval = super(ExceptionalDatabase, self).open()
        else:
            retval = super(ExceptionalDatabase, self).open(user=user, password=pwd)

        if retval == False:
            raise ValueError(self.lastError().text())

app = QApplication(sys.argv)

fid = open('example.db', 'w')
fid.close()

db = ExceptionalDatabase.addDatabase("QSQLITE")
db.setDatabaseName('example.db')
db.open()

db.close()

sys.exit(app.exec_())

我的主要问题是,我不知道该如何处理 addDatabase 方法,返回一个QSqlDatabase的实例。它返回一个QSqlDatabase的实例,但我想让它返回一个ExceptionalDatabase的实例。但我想让它返回一个ExceptionalDatabase的实例。我怎样才能从 addDatabase?

python pyqt pyqt5 qsqldatabase
1个回答
1
投票

首先addDatabase是一个静态方法,所以你不应该传递它自己。另一方面,一个变通的方法是建立QSqlDataBase的__class__。

class ExceptionalDatabase(QSqlDatabase):
    @staticmethod
    def addDatabase(*args, **kwargs):
        db = QSqlDatabase.addDatabase(*args, **kwargs)
        db.__class__ = ExceptionalDatabase
        return db

    def open(self, user=None, pwd=None):
        if user is None:
            retval = super(ExceptionalDatabase, self).open()
        else:
            retval = super(ExceptionalDatabase, self).open(user=user, password=pwd)
        if retval == False:
            raise ValueError(self.lastError().text())
© www.soinside.com 2019 - 2024. All rights reserved.