Mas Bagol
Mas Bagol

Reputation: 4617

How to get numbers of rows and columns using QtSql?

I have read the Qt documentation and can't find a direct way from the language itself to get numbers of rows and columns from the query result. The only way I can think of is using SELECT COUNT(*) FROM table_name in mysql query itself.

Like another connector (PHP, python, C++, etc.), as far as I know there's no direct way to get those values. Maybe I miss something. So, is there any possible way to do this? Maybe something like this:

int rows = db_connection->get_row_counts ();
int columns = db_connection->get_column_counts ();

Upvotes: 4

Views: 11307

Answers (2)

Jason Riek
Jason Riek

Reputation: 161

To add on to Nejat's answer, for an SQLite constructed database the size method will not work, and returns -1. I believe this is because of SQLite not supporting that type of query information (https://doc.qt.io/qt-5/qsqlquery.html#size).

Unless a cleaner method exists, this will work to get the row count:

 QSqlQuery query;
 int row_count = 0;
 
 // Run some query
 query.exec("SELECT * FROM SOME_TABLE");

 while(query.next())
     row_count++;

Also, one could take advantage of the SQL COUNT function:

   QSqlQuery query;
   int row_count = 0;

   query.exec("SELECT COUNT(*) FROM SOME_TABLE");

   if(query.first())
       row_count = query.value(0).toInt();

Upvotes: 2

Nejat
Nejat

Reputation: 32665

You can use QSqlQuery::size() to get the number of rows and QSqlRecord::count() to get the number of columns :

QSqlQuery qry;
qry.prepare("SELECT * FROM someTable");
qry.exec();

qDebug() << "Number of Rows: " << qry.size();
qDebug() << "Number of columns: " << qry.record().count();

Upvotes: 12

Related Questions