问题
The following problem has been discussed from time to time. However there was never a solution for the problem it self. As I found out there is a difference in iterating rows forward and backward. Forward iteration with QSqlQuery::next()
may result in only one row, however backward iteration with QSqlQuery::previous()
will always find all rows. Whether forward iteration is set explicitely or not, has no effect.
Edit: References removed
Concerning Qt documentation the right approach would be following:
QSqlQuery q = db.exec("SELECT * FROM Table");
while (q.next()) {
// Do something with row...
}
However this will result in only one row. Backward iteration will find all rows.
QSqlQuery q = db.exec("SELECT * FROM Table");
if (q.last()) {
do {
// Do something with row...
} while (q.previous());
}
Backward iteration could be very slow and should be avoided. Has anyone an idea why this does not work in forward iteration?
Edit: This behavior is not always reproduceable to me and sometimes it happens, sometimes not. The database contains more than one row in this case. The problem occurs exactly in this code snippets. Is there any one with the same problem?
Edit 2: It seems that the bug has been fixed in Qt 4.8.5.
My current environment: Windows 7 (SP1), Qt 4.8.5.
回答1:
It is simply false that the following problem has been discussed here several times. The references you provide have nothing to do with the behavior that you're seeing.
You likely have bugs in the code that replaces // Do something with row...
. You need to show that code in its entirety. You may also simply see the fact that there is in fact just a single row in your table at the time the problem occurs. This would be due to interaction with other code that modifies the database, but you never share that code, so how can we know?
If you're only iterating forward, you should call q.setForwardOnly(true)
as this will make things faster on some database backends.
来源:https://stackoverflow.com/questions/17066315/qsqlquery-for-sqlite-in-forward-iteration-with-next-will-only-find-one-row