How can I get sqlite error code from Qt

11,218

The best you can do with the Qt API itself is the following method:

int QSqlError::number() const

Returns the database-specific error number, or -1 if it cannot be determined.

See how the error codes from sqlite are handled in the driver codebase itself:

https://qt.gitorious.org/qt/qtbase/source/eb5c0f4b1266702c016b032e281bb92a3a642da6:src/sql/drivers/sqlite/qsql_sqlite.cpp#L324

You can see that the corresponding QSqlError constructor is used for that with passing the low-level error code to it as the last argument which you can obtain with the aforementioned method.

As you can see, it is not handling all the low-level errors similarly, but there is a default switch case in there for the rest. Even in the latter case, the errors are passed to the constructor.

You need to be aware of that, oftentimes, it cannot determine the exact low-level error in which case it will return -1 as per documentation.

Putting this into practice, you would be writing something like this:

QSqlQuery query;
query.exec(QString("select NAME from PEOPLE where AGE=%1").arg(age));
if (query.next())
{
} else {
    qDebug() << "SqLite error:" << query.lastError().text() << ", SqLite error code:" << query.lastError().number();
}
Share:
11,218
utarid
Author by

utarid

Updated on July 18, 2022

Comments

  • utarid
    utarid almost 2 years

    I use sqlite database in my Qt program.

    QSqlDatabase db;
    db = QsqlDatabase::addDatabase("QSQLITE");
    

    When I can not get data from sqlite db.lastError() function always return same thing

    QSqlError(-1, "Driver not Loaded", "Driver not loaded")
    

    How can I get sqlite error codes from Qt?

    upd1:

    QSqlQuery query;
    query.exec(QString("select NAME from PEOPLE where AGE=%1").arg(age));
    if(query.next())
    {
    }
    else
    {
        //check for sqlite error
    }