QSqlQuery :: value:未定位在有效记录上

时间:2013-12-28 11:23:40

标签: c++ sql qt pyqt qtsql

设置如下表格模型后:

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_())

内容显示正确,但在我编辑数据项后按Enter键,发生此错误:

QSqlQuery::value: not positioned on a valid record

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

注意:我没有使用

model->removeColumn(0)

这里。

1 个答案:

答案 0 :(得分: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):参数1具有意外类型'NoneType'”。

您可能需要以更友好的方式处理该场景。