我正在尝试从 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);
但是,我总是得到一个空行。表是空的还是满的条目并不重要。
open() 和prepare() 命令返回SQLITE_OK。
出了什么问题?
最佳答案
问题在于 while
语句末尾有一个分号,因此您的代码在 while
循环期间不执行任何操作,然后只会处理 NSLog("ROW");
作为 while
循环完成时它将执行的操作。因此,您的代码:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE);
{
NSLog(@"ROW");
}
相当于做:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE)
{
// do nothing
}
{
NSLog(@"ROW");
}
顺便说一句,您确实应该查看 sqlite3_step
返回代码,如果不是 SQLITE_ROW
或 SQLITE_DONE
,则显示错误,如果有的话。因此你的循环:
while (sqlite3_step(pStatementHandle) != SQLITE_DONE);
{
NSLog(@"ROW");
}
可能应该是:
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));
在您的原始再现中,如果出现错误,则永远不会退出 while
循环。
关于ios - 即使表为空,SQLite step() 也会返回 SQLITE_ROW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135109/