我正在尝试从sqlite数据库输出数据。我在PyQt的例子中做得很好,但它不起作用。数据库似乎已打开,但代码给出了错误,而实际上没有。你能告诉我为什么和如何解决这个问题吗?

#####################################################################
# test.py                                                           #
# ! /usr/bin/env python                                             #
#  -*- coding: utf-8 -*-                                            #
#####################################################################

from PyQt4 import QtGui, QtCore, QtSql
from src.database import DBase

class Test(QtGui.QMainWindow):

    def __init__(self):
        super(Test, self).__init__()

        self.tview = QtGui.QTableView()
        self.setCentralWidget(self.tview)
        model = QtSql.QSqlTableModel(self)
        model.setTable("person")
        model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
        model.select()
        model.setHeaderData(0, QtCore.Qt.Horizontal, QtCore.QObject.trUtf8(model, "№"))
        model.setHeaderData(1, QtCore.Qt.Horizontal, QtCore.QObject.trUtf8(model, "Name"))
        model.setHeaderData(2, QtCore.Qt.Horizontal, QtCore.QObject.trUtf8(model, "Lastname"))

        self.tview.setModel(model)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    db = DBase()
    db.connection_db()
    window = Test()
    window.resize(800, 600)
    window.show()
    sys.exit(app.exec_())

#####################################################################
# database.py                                                       #
# ! /usr/bin/env python                                             #
#  -*- coding: utf-8 -*-                                            #

from PyQt4 import QtSql, QtGui

class DBase():
    def connection_db(self):
        db=QtSql.QSqlDatabase.addDatabase("QSQLITE", "Base")
        db.setDatabaseName("db.sqlite")
        if db.open():
            print 'DataBase is now opened.'
            query = QtSql.QSqlQuery()
            query.exec_("create table 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')")
        return True

在输出中,它给出:
C:\Python27\python.exe D:test.py
QSqlQuery::exec: database not open
QSqlQuery::exec: database not open
QSqlQuery::exec: database not open
QSqlQuery::exec: database not open
QSqlQuery::exec: database not open
DataBase is now opened.

最佳答案

connection_db函数中,当调用QtSql.QSqlDatabase.addDatabase("QSQLITE", "Base")时,最后一个参数(“Base”)是连接名。
创建QSqlQuery时,不指定要使用的数据库实例,因此它使用应用程序的默认连接。因为给了连接名,所以应用程序没有默认连接,因此QSqlQuery看不到打开的数据库。
尝试在query = QtSql.QSqlQuery()函数中将query = QtSql.QSqlQuery(db)更改为connection_db。这让QSqlQuery知道它应该使用哪个连接。
文档:
QSqlDatabase.addDatabase
QSqlQuery

09-07 17:13