【问题标题】:SQLite Changes Not SavedSQLite 更改未保存
【发布时间】:2011-08-10 07:50:00
【问题描述】:

我在 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

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

【问题讨论】:

  • 你是否在 sqlite manager 中打开了你的数据库 n 检查插入后保存的记录?
  • 不,数据库在手机上。
  • 在将查询传递给 executeQuery 方法时使用 NSString stringWithFormat .....并将其转换为 UTF8String...试试吧

标签: iphone ios sqlite fmdb


【解决方案1】:

插入时您需要调用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];

【讨论】:

  • 该死,甚至没有注意到executeUpdate 方法。虽然我没有使用交易,但谢谢。
  • 你应该使用事务。它快了很多!关于 sqlite 性能的旧文档,也许您可​​以找到一些有用的信息:sqlite.org/speed.html
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多