2013-08-06 64 views
1

我试图插入一些值到我的sqlite数据库。数据库已经在手机上的doc文件夹中。我不知道发生了什么问题。我设置跟踪执行,但数据库告诉我,它没有任何错误。有人能帮我吗?iOS:SQLite插入查询不起作用

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年8月6日13:21:42.499 4Party [13018:907]的executeUpdate:INSERT INTO事件(标题,日期,地址,纬度,经度,位置,facebookID,picPath介绍)VALUES

+2

拉斐尔,如果你提供的有关'TRSharedLocalDatabase'更多信息,这将是有益的。你可以分享“openDatabase”方法的代码吗?确切地说,如果不了解更多关于代码的功能,将很难帮助您。 – Aaron

+0

openDatabase方法仅用于打开数据库。这里是:NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString * documentsDirectory = [paths objectAtIndex:0]; NSString * writableDBPath = [documentsDirectory stringByAppendingPathComponent:@“4PartyLocalSystem.sqlite”]; FMDatabase * database = [FMDatabase databaseWithPath:writableDBPath]; [数据库打开]; [数据库setTraceExecution:YES]; 返回数据库; –

+1

请通过编辑将问题添加到问题中,而不是将其添加到评论中。在评论 –

回答

1

两次观测(,,,,,@,,,????????):

  1. 你应该检查数据库的lastErrorMessage如果你有一个电子RROR。如果要在关闭数据库之前对数据库执行多个调用,那么它可以帮助将数据库指针存储在单独的变量中。

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

  2. 理想情况下,你应该在你的SQL与executeUpdate方法,而不是printf风格的占位符使用?占位符与executeUpdateWithFormat(见executeUpdateWithFormat documentation警告)。如果不是,则需要转义字符的文本字段(例如引号)将不会被使用。 (这也保护您免受SQL注入攻击。)

这样:

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]; 
+0

谢谢!我将FMDatabase存储在一个变量中,然后DB可以记录lastErrorMessage!现在我修复了查询! –