在PySide中将单个记录写入SQL数据库

时间:2017-09-22 20:47:14

标签: python qt pyside

我想从多个QT小部件构建记录并将其存储在数据库中。以下脚本运行时没有错误,但不存储记录。部分问题是我无法确定数据库中已存在的最后一个ID,但即使我手动设置了ID - 也没有写入任何内容。我在线使用insertRecord看过示例,但QT文档建议使用insertRow。请随时纠正我的方法。我是Python和Qt的新手。

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSql import *


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

        #Make Database
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        self.db.setDatabaseName('C:/Users/dle/Documents/example1.sqlite')
        self.db.open()
        self.db.transaction()
        self.db.exec_(
            'CREATE TABLE t1'
            '(id INTEGER PRIMARY KEY, f1 INTEGER NOT NULL, f2 INTEGER NOT NULL, f3 TEXT NOT NULL)'
        )
        self.db.exec_("INSERT INTO t1 VALUES(1, 10, 20, 'db works fine')")
        self.db.commit()

        #Create User Interface
        self.f1 = QLineEdit()
        self.f2 = QLineEdit()
        self.f3 = QLineEdit()

        self.storeButton = QPushButton("Store")
        self.storeButton.clicked.connect(self.doStore)

        vlayout = QVBoxLayout()
        vlayout.addWidget(self.f1)
        vlayout.addWidget(self.f2)
        vlayout.addWidget(self.f3)
        vlayout.addWidget(self.storeButton)

        widget = QWidget()
        widget.setLayout(vlayout)

        self.setCentralWidget(widget)

    def doStore(self):
        self.dbModel = QSqlTableModel(self)
        self.dbModel.setTable('t1')
        ID = self.dbModel.query().lastInsertId()    #this returns "None" even though last ID
                                                    #in table is 1
        thisRecord = QSqlRecord
        thisRecord = self.dbModel.record()
        thisRecord.setValue(0, ID)                  # Does not write, even if ID is integer
        print ID
        thisRecord.setValue(1, int(self.f1.text()))
        print int(self.f1.text())
        thisRecord.setValue(2, int(self.f2.text()))
        print int(self.f2.text())
        thisRecord.setValue(3, self.f3.text())
        print self.f3.text()
        print thisRecord
        self.dbModel.insertRecord(ID, thisRecord)   # Does not write, even if ID is integer
                                                    # Doesn't record field 0 already have ID?

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

如果要在表的末尾插入一行,则无需指明索引,因为根据docs

  

PySide.QtSql.QSqlTableModel.insertRecord(row,record

     

参数:

row - PySide.QtCore.int

record – PySide.QtSql.QSqlRecord 
     

返回类型:

PySide.QtCore.bool
     

在行之后插入记录。如果row为负数,则记录为   附在最后。致电PySide.QtSql.QSqlTableModel.insertRows()   和PySide.QtSql.QSqlTableModel.setRecord()内部。

     

如果可以插入行,则返回true,否则返回false。

从上面我们可以得出结论,我们应该只使用row = -1。

self.dbModel.insertRecord(-1, record)

最好的方法是创建模型一次,而不是每次调用doStore函数时,我们还必须在record()函数的帮助下使用模型的QSqlRecord,因为它加载了字段名称。 / p>

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        self.db.setDatabaseName('example1.sqlite')
        self.db.open()
        self.db.transaction()
        self.db.exec_(
            'CREATE TABLE t1'
            '(id INTEGER PRIMARY KEY, f1 INTEGER NOT NULL, f2 INTEGER NOT NULL, f3 TEXT NOT NULL)'
        )

        self.db.commit()
        self.db.exec_("INSERT INTO t1 VALUES(1, 10, 20, 'db works fine')")

        #Create User Interface
        [...]
        self.setCentralWidget(widget)

        self.dbModel = QSqlTableModel(self)
        self.dbModel.setTable('t1')

    def doStore(self):
        record = self.dbModel.record()
        record.setValue(1, int(self.f1.text()))
        record.setValue(2, int(self.f2.text()))
        record.setValue(3, self.f3.text())
        if not self.dbModel.insertRecord(-1, record):
            print(self.db.lastError().text())