使用FMDB插入表失败

时间:2013-02-21 11:11:57

标签: iphone ios sqlite fmdb

我试图在AppDelegate的数据库中插入一些值,但是每次无法插入数据时都会在应用程序中添加一些值。

代码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"db.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *results = [database executeQuery:@"select * from settings"];
if(results == nil)
{
 NSLog(@"Creating DB");
 [database beginTransaction];
 [database executeUpdate:@"create table settings(id int primary key, defaultaction text, beepsound text, vibrateeffect text, level text)"];
 NSString *query = [NSString stringWithFormat:@"insert into settings(id,defaultaction,beepsound,vibrateeffect,level) values (%d, '%@', '%@','%@','%@',)",11,@"auto", @"YES", @"YES", @"HIGH"];
 NSLog(@" %@",path);
 BOOL y= [database executeUpdate:query];
 if (!y)
 {
 NSLog(@"insert failed!!");
 }

 [database commit];
 [database close];


 }

2 个答案:

答案 0 :(得分:2)

我认为问题出在您的插入查询代码

NSString *query = [NSString stringWithFormat:@"insert into settings(id,defaultaction,beepsound,vibrateeffect,level) values (%d, '%@', '%@','%@','%@',)",11,@"auto", @"YES", @"YES", @"HIGH"];

你已经添加了一个,最后在values()中检查并删除最后一个,它肯定会起作用

NSString *query = [NSString stringWithFormat:@"insert into settings(id,defaultaction,beepsound,vibrateeffect,level) values (%d, '%@', '%@','%@','%@')",11,@"auto", @"YES", @"YES", @"HIGH"];

尝试此查询

答案 1 :(得分:1)

NSString *query = @"INSERT into settings(id,defaultaction,beepsound,vibrateeffect,level) 
VALUES (%@, %@, %@,%@,%@)";

BOOL y = [database executeUpdate:query, [NSNumber numberWithInt:11],@"auto", @"YES", @"YES", @"HIGH"];

尝试将查询更改为上述查询,如果表格已成功创建,则可以正常运行。

祝你好运。