Reputation: 1081
I am trying to fetch rows from a table in SQLite:
_tempPath = [[NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES)
objectAtIndex:0] stringByAppendingPathComponent:@"test.db"];
sqlite3 *pHandle;
sqlite3_stmt *pStatementHandle;
NSLog(@"OPEN: %i ", sqlite3_open([_tempPath UTF8String], &pHandle));
const char *query = "select * from Transactions";
NSLog(@"PREP: %i", sqlite3_prepare (pHandle, query, -1, &pStatementHandle, NULL));
while(sqlite3_step(pStatementHandle) != SQLITE_DONE);
{
NSLog(@"ROW");
}
sqlite3_finalize(pStatementHandle);
sqlite3_close(pHandle);
However, I am always getting exactly one empty row. Never matters whether the table is empty or full of entries.
The open() and prepare() commands are returning SQLITE_OK.
What is going wrong?
Upvotes: 2
Views: 3653
Reputation: 437592
The problem is that you have a semicolon at the end of the while
statement, so your code does nothing during the while
loop, and will then just treat the NSLog("ROW");
as something it will do when the while
loop is done. Thus, your code:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE);
{
NSLog(@"ROW");
}
is equivalent to doing:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE)
{
// do nothing
}
{
NSLog(@"ROW");
}
As an aside, you really should be looking at the sqlite3_step
return code, and if not SQLITE_ROW
or SQLITE_DONE
, display the error, if any. Thus your loop:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE);
{
NSLog(@"ROW");
}
should probably be:
int rc;
while ((rc = sqlite3_step(pStatementHandle)) == SQLITE_ROW) // note, no ";"
{
NSLog(@"ROW");
}
if (rc != SQLITE_DONE)
NSLog(@"%s: step error: %d: %s", __FUNCTION__, rc, sqlite3_errmsg(pHandle));
In your original rendition, if you had an error, would never exit the while
loop.
Upvotes: 3