iOS:SQLite插入查询不起作用

时间:2013-08-06 15:59:10

标签: ios sqlite fmdb

我试图将一些值插入我的sqlite数据库。数据库已经是手机上的doc文件夹。我无法弄清楚出了什么问题。我设置跟踪执行但db告诉我它没有任何错误。有人能帮助我吗?

if([[TRSharedLocalDatabase openDatabase] executeUpdateWithFormat:@"INSERT INTO event (title,date,address,latitude,longitude,location,facebookID,picPath,description) VALUES (%@,%@,%@,%@,%@,%@,%@,%@,%@)",event.title ,event.date, event.address, [NSNumber numberWithDouble:event.geoPoint.longitude], [NSNumber numberWithDouble:event.geoPoint.latitude], event.location.objectId, event.facebookID ,picPath ,event.description]) {    
    NSLog(@"Ok");  
} else {  
    NSLog(@"Not Ok");  
}  

+(FMDatabase *)openDatabase {  
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];  
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"4PartyLocalSystem.sqlite"];  
    **FMDatabase *database = [FMDatabase databaseWithPath:writableDBPath];**  
    [database open];  
    [database setTraceExecution:YES];  
    return database;   
}
  

2013-08-06 13:21:42.499 4Party [13018:907] executeUpdate:INSERT INTO事件(标题,日期,地址,纬度,经度,位置,facebookID,picPath,描述)VALUES(?,?,? ,?,?,的 @ 下,?,?,?)

1 个答案:

答案 0 :(得分:1)

两个观察结果:

  1. 如果您有错误,应检查数据库的lastErrorMessage。如果您在关闭数据库之前要对数据库进行多次调用,那么将数据库指针存储在单独的变量中会有所帮助。

    您绝对不希望与数据库的一个会话多次调用[TRSharedLocalDatabase openDatabase]。或者你可以重构它以符合单例模式。

  2. 理想情况下,您应该使用executeUpdate方法在SQL中使用?占位符,而不是executeUpdateWithFormat的printf样式占位符(请参阅executeUpdateWithFormat documentation中的警告)。如果没有,您的带有需要转义的字符的文本字段(例如引号)将不会。 (这也可以保护您免受SQL注入攻击。)

  3. 因此:

    FMDatabase *database = [TRSharedLocalDatabase openDatabase];
    if (!database) {
        NSLog(@"Unable to open database");
        return;
    }
    
    if([database executeUpdate:@"INSERT INTO event (title,date,address,latitude,longitude,location,facebookID,picPath,description) VALUES (?,?,?,?,?,?,?,?,?)",event.title ,event.date, event.address, [NSNumber numberWithDouble:event.geoPoint.longitude], [NSNumber numberWithDouble:event.geoPoint.latitude], event.location.objectId, event.facebookID ,picPath ,event.description]) {    
        NSLog(@"Ok");  
    } else {  
        NSLog(@"Not Ok: %@", [database lastErrorMessage]);  
    }  
    
    [database close];