0

I'm having trouble using SQLite in Qt. I created a table and performed a simple SELECT query.

#include <QtSql>

int main(int argc, char* argv[]) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("localhost");
    db.setDatabaseName(":memory:");
    if (!db.open())
        return -1;

    QSqlQuery query(db);
    bool success = query.exec("create table person (id int primary key, "
            "firstname varchar(20), lastname varchar(20))");    // Returns true
    bool valid = query.isValid();                   // Returns false, expected true
    success = query.exec("select * from person");   // Returns true
    valid = query.isValid();                        // Returns false, expected true
    bool select = query.isSelect();                 // Returns true
    int size = query.size();                        // Returns -1, should be 0

    return 0;
}

Why are these queries invalid even though query.exec returned true? Why is size not returning 0 here?

1 Answer 1

2

You haven't inserted any data into the table. The documentation for isValid() says:

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

Neither creating the table, nor selecting from an empty table, returns any records, so isValid() is expected to return false in both cases.

Try inserting some data into the table.

Note that size() is not supported by all database backends. Use db.driver()->hasFeature(QSqlDriver::QuerySize) to check if it is supported for your database. If it isn't supported, then size() will return -1.

Sign up to request clarification or add additional context in comments.

1 Comment

That explains my first question. But why am I getting -1 as the number of rows when I run my SELECT query? This behavior persists even when I do success = query.exec("insert into person (id, firstname, lastname) values (0, 'foo', 'foo')"); before I execute the SELECT statement. The docs also say that size() returns -1 if the database does not support reporting information about query sizes, but I'm not sure how I would verify that's the case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.