QSqlQuery::numRowsAffected() always returns 0 - why?
-
Hello,
Why numRowsAffected() always return 0?
@
// (...)
QSqlDatabase mydb;
// (...)
mydb = QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("./mydb.db");
// (...)void MyOwnSQLite::tables()
{
if(mydb.databaseName().length() >= 3) {
if(mydb.isOpen()) {
QSqlQuery tables;
tables.exec("SELECT name FROM sqlite_master WHERE type IN ('table')");
qDebug() << "Query returned:" << tables.numRowsAffected() << "results";
if(tables.numRowsAffected() < 0) {
qDebug() << "Query error:" << tables.lastError().text();
}
else {
while(tables.next()) {
QString name = tables.value(0).toString();
qDebug() << "\t- " << name; // display table name
}
}
}
else {
qDebug() << "No opened database!";
}
}
else {
qDebug() << "No database object";
}
}
@Debug:
@
Query returned: 0 results- "friends"
- "enemies"
@
-
According to the doc for "numRowsAffected()":http://qt-project.org/doc/qt-5.0/qtsql/qsqlquery.html#numRowsAffected, for SELECT statements you should use "size()":http://qt-project.org/doc/qt-5.0/qtsql/qsqlquery.html#size.
-
Ok, but size() returns -1, I guess because query is not active. So how to keep query active or how to force use numRowsAffected() in my case?
Update:
In Google's opinion SQLite doesn't support any size()-like methods. So my question is - Do I have to implement my own low-efficient method or is there any other better way already implemented? -
I've solved similar problem by using a separate query which returns number of rows. I'm sure that exists much better solutions but that variant fully satisfied me.
@if(mydb.isOpen()) {
QSqlQuery tables;
int iNumOfRows=tables.exec("SELECT count(*) FROM sqlite_master WHERE type IN ('table')");
qDebug() << "Query returned:" << iNumOfRows << "results";
if(tables.lastError().isValid()) {
qDebug() << "Query error:" << tables.lastError().text();
}
else {
tables.exec("SELECT name FROM sqlite_master WHERE type IN ('table')");
while(tables.next()) {
QString name = tables.value(0).toString();
qDebug() << "\t- " << name; // display table name
}
}@ -
Was ready to post slip's answer :) . Use this approach, should do what you want.