应用程序重启后,Sqlite插件会丢失

时间:2011-06-28 10:42:42

标签: iphone objective-c sqlite

这是插入代码。它工作正常,直到我关闭应用程序并再次启动它,然后所有更改都消失了。我没有看到任何错误,可能是某些特定于iPhone的问题吗?

const char *sql = "INSERT INTO offers "
                  "(OfferId, AddressId, ShortDescription, LongDescription, TimeStart, TimeEnd, Created, LastEdit) "
                  " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";


sqlite3_stmt *stmt;
int returnValue = sqlite3_prepare(db, sql, -1, &stmt, NULL);
if(returnValue == SQLITE_OK) {
    for(NSDictionary *offer in offers) {
        sqlite3_bind_int(stmt, 1, [[offer valueForKey:@"OfferId"] intValue]);
        sqlite3_bind_int(stmt, 2, [[offer valueForKey:@"AddressId"] intValue]);
        sqlite3_bind_text(stmt, 3, [[offer valueForKey:@"ShortDescription"] UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(stmt, 4, [[offer valueForKey:@"LongDescription"] UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(stmt, 5, [[offer valueForKey:@"TimeStart"] intValue]);
        sqlite3_bind_int(stmt, 6, [[offer valueForKey:@"TimeEnd"] intValue]);
        sqlite3_bind_int(stmt, 7, [[offer valueForKey:@"Created"] intValue]);
        sqlite3_bind_int(stmt, 8, [[offer valueForKey:@"LastEdit"] intValue]);

        if(sqlite3_step(stmt) != SQLITE_DONE)
            NSLog(@"instertOffers -> sql-error: %s", sqlite3_errmsg(db));
        else
            NSLog(@"added offer with id: %@", [offer valueForKey:@"OfferId"]);

        sqlite3_reset(stmt);
    }
} else {
    NSLog(@"instertOffers -> sql-error: %s", sqlite3_errmsg(db));
}

sqlite3_finalize(stmt);
sqlite3_close(db);

2 个答案:

答案 0 :(得分:5)

SQLite数据库文件是否在AppBundle中,如果是这样,如果要进行更改,则需要将其复制到文档目录。 您无法写入应用包中的任何文件。

答案 1 :(得分:1)

将数据库写入文件管理器:

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *dbPath = [self getDatabasePath];
    BOOL success = [fileManager fileExistsAtPath:dbPath]; 

    if(!success) {

        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yourDB.sqlite"];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

        if (!success) 
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }

从文件管理器中获取数据库:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:@"yourDB.sqlite"];

通过这种方式,您下次打开数据库时将保存更改。我宁愿建议使用FMDatabase包装器,用Obj C编写sqlite。这是FMDatabase的链接: http://code.google.com/p/flycode/source/browse/trunk/fmdb

希望它有所帮助!!

相关问题