尝试返回iPhone上的SQLite中是否存在记录,但我不断收到“未知错误”。
selectStmt static sqlite3_stmt *selectStmt = nil;
在此使用if(selectStmt) sqlite3_finalize(selectStmt);
,只有在应用程序终止时才会执行。这个功能适用于删除语句和插入语句,所以我猜测下面的逻辑有问题吗?
- (BOOL) doesBookExist {
if(selectStmt == nil) {
const char *sql = "select count(*) from books where isbn = ?";
if(sqlite3_prepare_v2(database, sql, -1, &selectStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating select statement. '%s'", sqlite3_errmsg(database));
}
//When binding parameters, index starts from 1 and not zero.
int count = sqlite3_bind_text(selectStmt, 1, [isbn UTF8String], -1, SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(selectStmt))
NSAssert1(0, @"Error while selecting. '%s'", sqlite3_errmsg(database));
sqlite3_reset(selectStmt);
return (count > 0);
}
答案 0 :(得分:2)
sqlite3_bind_text
返回成功/错误代码,而不是任何查询的结果。并且step应返回SQLITE_ROW
,因为您有一行结果数据(无论计数是0还是更多)。似乎有错误,因为当正确的值为SQLITE_DONE
时,您期待SQLITE_ROW
。然后,要获得计数,您需要在执行步骤后使用sqlite3_column_int
。如下所示:
int bind_res = sqlite3_bind_text(selectStmt, 1, [isbn UTF8String], -1, SQLITE_TRANSIENT);
if (SQLITE_OK != bind_res)
{
// log error, return...
}
// One row of result data, so step should return SQLITE_ROW
if (SQLITE_ROW != sqlite3_step(selectStmt))
{
NSAssert1(0, @"Error while selecting. '%s'", sqlite3_errmsg(database));
// log error, return
}
int count = sqlite3_column_int(selectStmt, 0);