QSqlQuery, how to iterate through a record?
-
I am using QSqlQuery to perform a query, previously I have supplied an array of field names, however I want to replace this by iterating through a record and getting each field automatically.
I've searched online and cannot find an example, how do I achieve this?
-
@SPlatten Right there in documentation: https://doc.qt.io/qt-5/qsqlquery.html
QSqlQuery query("SELECT country FROM artist"); while (query.next()) { QString country = query.value(0).toString(); doSomething(country); }
With query.value(INDEX) you access the field INDEX. You can also use https://doc.qt.io/qt-5/qsqlquery.html#value-1 to access columns by name...
If you mean you don't want to hard code the column names, but instead make it generic you can use "DESCRIE table_name" SQL command to get information about the table.
-
@SPlatten said in QSqlQuery, how to iterate through a record?:
previously I have supplied an array of field names, however I want to replace this by iterating through a record and getting each field automatically.
I don't really understand what your are talking about?
Do you want to know position of each field of your requests or loop through each record?If you want to get position of each field you can you
QSqlQuery::record()
:
for example:if(query.exec("SELECT * from position WHERE ID > 100")) { const auto rec = query.record(); const int col_X = rec.indexOf("X"); const int col_Y = rec.indexOf("Y"); while(query.next()) { int X = query.value(col_X).toInt(); int Y = query.value(col_Y).toInt(); } }
For more details see documentation ==> https://doc.qt.io/qt-5/qsqlquery.html#record