2011-08-10 70 views
2

我在iPhone上使用iOS 4中的SQLite,但我的更新语句所做的更改未保存。起初以为退出应用程序可能会以某种方式删除数据库,但在同一会话期间甚至不会保留。初始化我的数据库的代码是(使用FMDB):未保存SQLite更改

-(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;  
} 

这些方法称为创建数据库Both,然后插入到表我打电话:

  [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 

至于我可以看到我不丢失任何东西,而数据库似乎处于可写位置。

+0

具有u打开乌尔分贝sqlite的经理ñ检查插入后保存的记录? – booleanBoy

+0

不,数据库在手机上。 – Echilon

+0

使用NSString stringWithFormat同时将查询传递给executeQuery方法.....并且还将其转换为UTF8String ...只是试试 – booleanBoy

回答

5

我弄错了你的错误... 插入你需要调用执行更新不执行查询。另外,在插入r时调用beginTransaction然后提交。

难道就这样..

[_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]; 

希望这将帮助你..

+0

该死的,甚至没有注意到'executeUpdate'方法。虽然我没有使用交易,但谢谢。 – Echilon

+1

您应该使用交易。速度要快得多!一个关于sqlite性能的旧文档,也许你可以找到一些有用的信息:http://www.sqlite.org/speed.html –