使用 Qt 从 SQLite 中选择 [英] Select from SQLite with Qt
问题描述
我尝试在 Linux 上的 Qt 4.5.3 上处理 SQLite 数据库.我已经创建了数据库.
I try to deal with SQLite database on Qt 4.5.3 on Linux. I've already created the databsae.
然后,我尝试在 Qt 上执行选择:
Then, I try to perform select on Qt:
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(filename); // Here is FULL path to the database. I've checked it twice :)
bool ok = db.open();
qDebug() << db.tables();
QSqlQuery query;
query.exec("select * from lessons");
qDebug() << query.size();
qDebug() << query.isSelect();
qDebug() << query.isValid();
但是调试控制台说:
("lessons", "weeklessons", "weeks")
-1
true
false
为什么什么都不选?我做错了什么?
Why it's select nothing? What I have doing wrong?
推荐答案
如果查询定位在有效记录上,isValid() 方法返回 true,但在调用 exec() 后,它不是:您必须移动首先到有效记录,例如使用 query.first() 或 query.next().请参阅 Qt 文档:http://doc.qt.io/archives/4.6/qsqlquery.html
The isValid() method returns true if the query is positionned on a valid record, but after calling exec(), it isn't : you have to move to a valid record first, for example with query.first() or query.next(). See Qt docs : http://doc.qt.io/archives/4.6/qsqlquery.html
返回 -1 的 size() 并不意味着没有结果:SQLite 是无法直接获得查询大小的数据库之一(查看 QSqlDriver::hasFeature() 的文档).您可以检查是否返回了行并使用循环和 query.next() 查找大小.
The size() returning -1 doesn't mean there is no result : SQLite is one of the databases for which the size of the query is not directly available (look in the documentation for QSqlDriver::hasFeature()). You can check that rows are returned and find the size with a loop and query.next().
根据您想对选择的结果做什么,您也可以使用 QSqlQueryModel 而不是 QSqlQuery.
Depending on what you want to do with the result of your select, you could also use QSqlQueryModel instead of QSqlQuery.
这篇关于使用 Qt 从 SQLite 中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!