Вопрос

Im trying to insert some values to my sqlite database. The db is already of the doc folder on the phone. I cant figure out what is going wrong. I set trace executing but the db tells me that it does not have any error. Can someone help me?

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 event (title,date,address,latitude,longitude,location,facebookID,picPath,description) VALUES (?,?,?,?,?,@,?,?,?)

Это было полезно?

Решение

Two observations:

  1. You should examine the lastErrorMessage of the database if you have an error. It helps if you store the database pointer in a separate variable if you're going to do multiple calls to the database before closing it.

    You definitely don't want to call [TRSharedLocalDatabase openDatabase] multiple times for one session with your database. Or you could refactor it to conform to a singleton pattern.

  2. Ideally, you should use ? placeholders in your SQL with executeUpdate method, not printf-style placeholders with executeUpdateWithFormat (see the warning in the executeUpdateWithFormat documentation). If not, your text fields with characters that need to be escaped (e.g. quotation mark) won't be. (This also protects you against SQL injection attacks.)

Thus:

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];
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top