QTSql Read row by row
-
@ranger281
HiQSqlQuery query("SELECT country FROM artist"); while (query.next()) { QString country = query.value(0).toString(); doSomething(country); }
-
How can I load the driver first and then execute the query?
QSqlQuery query(db); query = QSqlQuery("SELECT member FROM Database"); while (query.next()) { QString row = query.value(0).toString(); cout << row.toStdString(); }
This is not working
-
@ranger281
you dont need to give it db as paramter.
just open the database somewhere and u can use
QSqlQuery in whole program. -
In that case I get this error:
QSqlQuery::exec: database not open
db is already opened (i added db.open() before creating query).
-
@ranger281
Where did you do @mrjj's "just open the database somewhere"?
You've edited your post --- now show the code where you open the database and how it relates to where you execute the query. [BTW, did you check it actually opened correctly?QSqlDatabase::open()
returns a value...] -
@JonB I opened db in other function called from main and tried doing the same in this code, but it does not work.
db.open(); QSqlQuery query("SELECT member FROM Database"); while (query.next()) { QString row = query.value(0).toString(); cout << row.toStdString(); }
-
@ranger281 What does http://doc.qt.io/qt-5/qsqldatabase.html#open return?
-
@jsulm This code returns 2:
if (db.isOpen()) return 2;
I will add the QSqlDatabase::open() in a moment.
Edit:
This code:if (db.open()) cout << "opened\n"; QSqlQuery query("SELECT member FROM Database"); while (query.next()) { QString row = query.value(0).toString(); cout << row.toStdString(); }
Returns:
opened QSqlQuery::exec: database not open
When I open the db only in the other function it returns the same error.
-
QSqlDatabase db; db = QSqlDatabase::addDatabase("QMYSQL", "SQLFileDatabase"); db.setHostName(QString::fromStdString(host)); db.setDatabaseName(QString::fromStdString(name)); db.setUserName(QString::fromStdString(user)); db.setPassword(QString::fromStdString(password)); db.open();
-
Then check whether the
open
call is successful here and print the error if it's not the case.Also:
- What version of Qt are you using ?
- What platform ?
- Did you install the MySQL client libraries ?
-
This post is deleted!
-
The @Gerd 's solution works. Reading row by row too.
Thank you all for help.