Search code examples
pythonpython-3.xpyqtpyqt5qsqlquery

explanation of isValid() in QSqlQuery


Hi i m unable to understand the explanation of isValid method of QSqlQuery in Qt.

The query always returns False for isValid()

and true for next(),first() etc

I checked for lastErrors as well if any, none were there

I m new to qt , can anyone explain me what is meant by

bool QSqlQuery::isValid () const

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

Code --

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

Solution

  • The documentation does not explain the concept correctly, but if we review the source code:

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

    d->sqlResult is a QSqlResult, so if we check the docs of the 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.

    And there is clearly understood what returns QSqlQuery::isValid(), will return false in 2 cases, the first is when data has not yet been requested for the result, and the second when there is no data.

    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")
    

    Results:

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

    It is clear that before requesting data, in this example we use query.value(0), it is False, it is True while there is data, and it is False again when there is no data.