0

像这样设置表模型后:

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


def createConnection(driverType, databaseName, hostName=None, userName=None, password=None):
    db = QSqlDatabase.addDatabase(driverType);
    db.setDatabaseName(databaseName)
    db.setHostName(hostName);
    db.setUserName(userName);
    db.setPassword(password)
    if (db.open() == False):
        QMessageBox.critical(None, "Database Error", db.lastError().text())
        return False
    return db


if __name__ == '__main__':

    app = QApplication(sys.argv)
    con = createConnection('QSQLITE', "testdatabase.db")

    qry = QSqlQuery()
    qry.setForwardOnly(True)

    qry.prepare("CREATE TABLE IF NOT EXISTS names (id INTEGER UNIQUE PRIMARY KEY, firstname VARCHAR(30), lastname VARCHAR(30))");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Table createdFalse==");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (1, 'John', 'Doe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (2, 'Jane', 'Doe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (3, 'James', 'Doe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (4, 'Judy', 'Doe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (5, 'Richard', 'Roe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (6, 'Jane', 'Roe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (7, 'John', 'Noakes')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (8, 'Donna', 'Doe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (9, 'Ralph', 'Roe')");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("Inserted!");

    qry.prepare("SELECT id, firstname, lastname FROM names");
    if (qry.exec_() ==False):
        print(qry.lastError().text())
    else:
        print("SelectedFalse==");

    print(con.tables(), con.primaryIndex('names').name(), con.record('names'))  # #########################

    while (qry.next()):
#        print(qry.boundValues())
        country = qry.value(1)
        print(country)

    rec = qry.record()
    cols = rec.count();

    for c in range(cols):
        print("Column {}: {}" .format(c, rec.fieldName(c)))

    qry.prepare("SELECT firstname, lastname FROM names WHERE lastname = 'Roe'" );
    if (qry.exec_()==False ):
        print(qry.lastError().text())
    else:
        print("SelectedFalse==" );

    qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (:id, :firstname, :lastname)" );
    qry.bindValue(":id", 9 );
    qry.bindValue(":firstname", "Ralph" );
    qry.bindValue(":lastname", "Roe" );
    if(False==qry.exec_()):
        print(qry.lastError().text())
    else:
      print("Inserted!" );

    qry.prepare("CREATE TABLE IF NOT EXISTS salaries (id INTEGER UNIQUE PRIMARY KEY, annual INTEGER)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (1, 1000)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (2, 900)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (3, 900)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (5, 1100)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (6, 1000)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (8, 1200)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("INSERT INTO salaries (id, annual) VALUES (9, 1200)" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:
      print("Inserted!" );

    qry.prepare("SELECT * FROM salaries" );
    if(False==qry.exec_()):
      print(qry.lastError())
    else:

      print("SelectedFalse==" );



#    con.close()

#    model = QSqlQueryModel();
#    model.setQuery( "SELECT firstname, lastname FROM names" );


    model = QSqlRelationalTableModel()
    model.setTable( "names" );
    model.setRelation( 0, QSqlRelation( "salaries", "id", "annual" ) );
    model.select();
#    model.setHeaderData( 0, Qt.Horizontal, ("Annual Pay") );
#    model.setHeaderData( 0, Qt.Horizontal, ("Annual Pay") );
#    model.setHeaderData( 1, Qt.Horizontal, ("First Name") );
#    model.setHeaderData( 2, Qt.Horizontal, ("Last Name") );
#    


#    model = QSqlTableModel()
    print(model.editStrategy() )
#    model.setTable( "names" );
#    model.setFilter( "lastname = 'Doe'" );
#    model.select();
#    model.removeColumn( 0 );

    view =  QTableView();
    view.setModel( model );
    view.show();

    sys.exit(app.exec_())

内容显示正确,但在我编辑数据项然后按回车后,出现此错误:

QSqlQuery::value: not positioned on a valid record

当我关闭应用程序并重新启动它时,我发现我上次所做的编辑没有存储到数据库中,任何人都可以在这里解决我的问题。

注意:我没有使用

model->removeColumn(0)

这里。

4

1 回答 1

1

这些行是有问题的:

qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (:id, :firstname, :lastname)" )
qry.bindValue(":id", 9 );
qry.bindValue(":firstname", "Ralph" );
qry.bindValue(":lastname", "Roe" );

您基本上再次插入之前插入的内容:

qry.prepare("INSERT INTO names (id, firstname, lastname) VALUES (9, 'Ralph', 'Roe')");
if (qry.exec_() ==False):
    print(qry.lastError().text())
else:
    print("Inserted!");

最有趣的重复是id在这里,这就是为什么您在命令行上收到以下错误:

UNIQUE constraint failed: names.id Unable to fetch row

设计它拒绝具有相同唯一标识符的数据库条目,否则它将不再是唯一的,对吗?

合理的解决方案是将代码中的 id 9 增加到 10,因为您似乎保留了 1-9 的 id。有一次,我对您的代码进行了更改,它不再产生上述错误。

另请注意,您在未指定主机名的情况下调用 createConnection 函数会导致 python 类型错误,例如:“TypeError: QSqlDatabase.setHostName(QString): argument 1 has unexpected type 'NoneType'”。

您可能需要以更加用户友好的方式处理这种情况。

于 2013-12-28T11:36:06.997 回答