3

我在 iPhone 上的 iOS 4 中使用 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;    
}

这两种方法都被调用来创建数据库,然后插入到我调用的表中:

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

问题是,当我阅读MyTable下面的语句时,我再也没有得到任何回报:

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

据我所见,我没有遗漏任何东西,而且数据库似乎位于可写位置。

4

1 回答 1

6

插入时,您需要调用executeUpdatenot executeQuery。你也应该打电话beginTransactionthen 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];
于 2011-08-10T09:56:05.097 回答