QSqlQuery中isValid()的解释

explanation of isValid() in QSqlQuery

你好我无法理解Qt中QSqlQuery的isValid方法的解释

查询总是 returns False for isValid()

对于 next()、first() 等都是正确的

我也检查了 lastErrors,如果有的话,none 在那里

我是 qt 的新手,谁能解释一下

是什么意思
bool QSqlQuery::isValid () const

Returns true if the query is currently positioned on a valid record; otherwise returns false.

代码--

query = QtSql.QSqlQuery()
query.exec_("select * from test.PG_Details where PG_Id = 1")

print("Bool->",query.isValid())     // Return FALSE
print("Next->",query.next())        // Returns TRUE
print("LE->",query.lastError().text())     //Returns Blank

文档没有正确解释这个概念,但是如果我们查看 source code:

bool QSqlQuery::isValid() const
{
    return d->sqlResult->isValid();
}

d->sqlResult 是一个 QSqlResult,所以如果我们查看 isValid() method of QSqlResult 的文档:

bool QSqlResult::isValid() const

Returns true if the result is positioned on a valid record (that is, the result is not positioned before the first or after the last record); otherwise returns false.

并且很清楚returns QSqlQuery::isValid(), will return false 在2种情况下,第一种是结果还没有请求数据的时候,而没有数据时秒

import sys
from PyQt5 import QtSql

def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        return False

    query = QtSql.QSqlQuery()
    query.exec_("create table PG_Details (PG_Id int, firstname varchar(20), lastname varchar(20))")

    query.exec_("insert into PG_Details values(1, 'Danny', 'Young')")
    query.exec_("insert into PG_Details values(2, 'Christine', 'Holand')")
    query.exec_("insert into PG_Details values(1, 'Lars', 'Gordon')")
    query.exec_("insert into PG_Details values(2, 'Roberto', 'Robitaille')")
    query.exec_("insert into PG_Details values(1, 'Maria', 'Papadopoulos')")

    return True

if __name__ == '__main__':
    if not createConnection():
        sys.exit(-1)

    query = QtSql.QSqlQuery()

    if not query.exec_("select * from PG_Details where PG_Id = 1"):
        print("Error: ", query.lastError().text())

    print("isValid: ", query.isValid(), "before")

    while query.next():
        res = query.value(0)
        print("isValid: ", query.isValid())

    print("isValid: ", query.isValid(), "after")

结果:

isValid:  False before
isValid:  True
isValid:  True
isValid:  True
isValid:  False after

很明显在请求数据之前,本例中我们使用query.value(0),为False,有数据时为True,无数据时又为False。