iOS中的SQLite表现得很奇怪

时间:2012-04-16 04:25:39

标签: iphone ios sqlite

我是iOS开发的新手,最近我在iOS SQLite上遇到了一些奇怪的行为。我有一个允许用户将记录插入SQLite DB的应用程序。该应用程序工作正常,但有一段时间后,用户创建的记录会以某种方式消失。当发生这种情况时,随后当我尝试创建新记录时,它不会将记录存储在DB中。执行insert语句时没有错误但数据不是insert。下面是执行记录插入逻辑的函数。请帮忙,谢谢。

+ (BOOL)insertAutoRecord:(AutoRecord *)record{
  BOOL ret = NO;

  NSString *query = [NSString stringWithFormat:@"insert into %@ (%@, %@, %@, %@, %@, %@, %@) values ('%@', %d, %d, '%@', %d, %d, %d)",
                   TABLE_NAME_AUTOMATIC_RECORDS,
                   COL_NAME_AUTO_RECORD_SENSOR_ID,
                   COL_NAME_AUTO_RECORD_MONITOR_START_DATE,
                   COL_NAME_AUTO_RECORD_MONITOR_END_DATE, 
                   COL_NAME_AUTO_RECORD_FREE_TEXT,
                   COL_NAME_AUTO_RECORD_CREATE_DATE,
                   COL_NAME_AUTO_RECORD_KID_ID,
                   COL_NAME_AUTO_RECORD_LAST_SYNC_DATE,
                   record.sensorId,
                   record.startDate,
                   record.endDate,
                   [record.freeText stringByReplacingOccurrencesOfString:@"'" withString:@"''"],
                   record.createDate,
                   record.kidId,
                   0];

 KSDelegate *appDelegate = (KSDelegate *)[[UIApplication sharedApplication] delegate];
 sqlite3 *dbHandler = appDelegate.dbHandler;

 sqlite3_stmt *stmt;
 const char *insert_stmt = [query UTF8String];

 sqlite3_prepare_v2(dbHandler, insert_stmt, -1, &stmt, NULL);
 if (sqlite3_step(stmt) == SQLITE_DONE)
 {
    ret = YES;
 }
 else
 {
    ret = NO;
 }
 sqlite3_finalize(stmt);


 if(ret == NO)
    return NO;

 query = [NSString stringWithFormat:@"select last_insert_rowid()"];

 if(sqlite3_prepare(dbHandler, [query UTF8String], -1, &stmt, nil) != SQLITE_OK)
    return NO;

 if(sqlite3_step(stmt) == SQLITE_ROW)
 {
    int recordId = (int)sqlite3_column_int(stmt, 0);
    record.recordId = recordId;
 }
 else
    ret = NO;

 sqlite3_finalize(stmt);

 return ret;
}

1 个答案:

答案 0 :(得分:1)

这里是SQlite的完美示例和示例代码。我建议您仔细阅读...

SQlite tutorial for iOS Developer