SQLite更改未保存

Ech*_*lon 2 sqlite iphone fmdb ios

我在iPhone上使用iOS4中的SQLite,但我的更新语句所做的更改未保存.起初认为可能退出应用程序可能会以某种方式删除数据库,但它们甚至在同一会话期间都没有持久化.初始化我的数据库的代码是(使用FMDB):

-(SQLiteDal*) init {
    pool = [[NSAutoreleasePool alloc] init];

    self = [super init];
    if(self !=  nil){
        // Setup some globals
        NSString *databaseName = [self getDbPath];
        NSLog([NSString stringWithFormat:@"db path: %@", databaseName]);
        db = (FMDatabase *)[FMDatabase databaseWithPath:databaseName];
        if (![db open]) {
            NSLog(@"Could not open db.");
            [pool release];
            return 0;
        }
    }
    //[self checkAndCreateDatabase];
    return self;
}

#pragma mark DB Maintenance
-(NSString *)getDbPath {
    NSString *databaseName = @"myapp.db";

    // Get the path to the documents directory and append the databaseName
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databaseName = [documentsDir stringByAppendingPathComponent:databaseName];
    return databaseName;    
}
Run Code Online (Sandbox Code Playgroud)

这两种方法打电话来创建数据库,然后插入到表我打电话:

            [db executeQuery:@"INSERT INTO MyTable (Name, Description, Area, Price, ID) VALUES (?,?,?,?,?)", 
             f.Name,
             f.description,
             f.area,
             f.price,
             f.id];
Run Code Online (Sandbox Code Playgroud)

问题是,当我MyTable使用下面的陈述来阅读时,我从来没有得到任何回报:

    FMResultSet *rs = [db executeQuery:@"SELECT * FROM MyTable WHERE ID = ?", id];
    while ([rs next]) {
        //.. this is never called
Run Code Online (Sandbox Code Playgroud)

据我所知,我没有遗漏任何东西,数据库似乎处于可写的位置.

iCo*_*777 5

插入时,你需要调用executeUpdate没有executeQuery.你应该打电话beginTransaction然后commit,像这样:

[_dbPointer beginTransaction];
BOOL isInserted = [_dbPointer executeUpdate:[NSString stringWithFormat:@"INSERT INTO  MyTable (Name, Description, Area, Price, ID) VALUES(?,?,?,?,?);", f.Name,
         f.description,
         f.area,
         f.price,
         f.id]];
[_dbPointer commit];
Run Code Online (Sandbox Code Playgroud)