Reputation: 51
My QT SQL select doesn't return any data:
//connect DB
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");
if (!db.open())
{
qDebug() << "Connection error!!!";
}
QSqlQuery query;
query.prepare("SELECT * FROM transportas");
if (!query.exec())
{
qDebug() << "SQL error: "<< query.lastError().text() << endl;
}
qDebug() << query.executedQuery();
qDebug() << query.result();
qDebug() << query.size();
query.first();
while (query.next())
{
qDebug() << "found " << endl;
}
Tried to write path like this - C:\temp\atsakymai_1.db, but result the same:
query.result - 0x3c6ed8
query.size - -1
I had google all day to find any solution, but it didn't help, still have no idea what is wrong with my code.
Tried INSERT before SELECT, INSERT works without errors, but SELECT still return nothing:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");
if (!db.open())
{
qDebug() << "error!!!";
}
QSqlQuery query(db);
query.exec("insert into t_transportas (transportas) values ('asdasd22')");
query.exec("SELECT id, transportas FROM 't_transportas'");
qDebug() << query.executedQuery();
qDebug() << query.result();
qDebug() << query.size();
if (query.size()> 0)
{
qDebug() << "found " <<
}
Upvotes: 0
Views: 4361
Reputation: 51
Found where problem is, QSqlQuery::size() function not working, it always return -1. So don't use this function to find rows count. In place of this use .first() .next() functions. This code works correctly:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:/temp/atsakymai_1.db");
if (!db.open())
{
qDebug() << "error!!!";
}
QSqlQuery query(db);
query.prepare("SELECT id, transportas FROM 't_transportas'");
if (!query.exec())
{
qDebug() << "SQL error: "<< query.lastError().text() << endl;
}
query.first();
qDebug() << "found: " << endl;
while (query.next())
{
qDebug() << query.value("id").toString() << ". " << query.value("transportas").toString();
}
Asnwer found here: QtSQL + Sqlite and support for .size() function?
Upvotes: 2