无法使用iOS将数据插入sqlite3数据库

时间:2013-01-10 12:15:13

标签: iphone ios objective-c ipad sqlite

使用MacOS终端我创建了一个数据库名称数据库。sql并插入了一些记录。使用iOS我可以检索插入的值。

但是使用iOS代码我试图将记录插入数据库,它不会进入数据库中的记录。

我是否需要设置一些权限?这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self openDB];
}

-(IBAction)save:(id)sender{

    [self insertRecordIntoTableNamed:@"Contacts" 
                         field1Value:fname.text
                         field2Value:lname.text
                         field3Value:comp.text 
                         field4Value:email.text 
                         field5Value:pnumber.text 
                         field6Value:mnumber.text 
                         field7Value:add.text 
                         field8Value:city.text 
                         field9Value:state.text];
}


-(void)openDB{
    NSString *sqlfile=[[NSBundle mainBundle]pathForResource:@"database" ofType:@"sql"];

    if(sqlite3_open([sqlfile UTF8String], &db)!= SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"Database connected");
        NSAssert(0,@"Database failed to open");
    }
    else
    {
        NSLog(@"Database connected");
    }
}


-(void) insertRecordIntoTableNamed:(NSString *) tableName
                       field1Value:(NSString *) field1Value
                       field2Value:(NSString *) field2Value
                       field3Value:(NSString *) field3Value
                       field4Value:(NSString *) field4Value
                       field5Value:(NSString *) field5Value
                       field6Value:(NSString *) field6Value
                       field7Value:(NSString *) field7Value
                       field8Value:(NSString *) field8Value
                       field9Value:(NSString *) field9Value {

    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ VALUES ('%@','%@','%@','%@',%@,%@,'%@','%@','%@');",tableName, field1Value, field2Value,field3Value,field4Value,field5Value,field6Value,field7Value ,field8Value,field9Value];


    NSLog(@"%@",sql);

    // char *err;
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)== SQLITE_OK)
    {
        if (SQLITE_DONE!=sqlite3_step(statement))
        {
            sqlite3_close(db);
            NSAssert(0, @"Error updating table.");
        }
        else{
            NSLog(@"Success");
            NSLog(@"%@",sql);
        }
    }
    sqlite3_finalize(statement);
}

@end

这就是我所做的:

  1. 使用CHMOD

  2. 更改文件夹和路径权限
  3. sqlite3_exec()拆分为sqlite3_prepare()sqlite3_step()sqlite3_finalize() - 我得到相同的输出 - 创建查询但未在数据库中创建记录

  4. 我能够检索记录信息

2 个答案:

答案 0 :(得分:2)

您无法写入资源包中的数据库。您需要复制它然后再使用它。

以下是我成功使用的一些代码(关键是ensureDatabasePrepared从资源复制的地方):

- (BOOL)ensureDatabaseOpen: (NSError **)error
{
    // already created db connection
    if (_contactDb != nil)
    {
        return YES;
    }

    NSLog(@">> ContactManager::ensureDatabaseOpen");    
    if (![self ensureDatabasePrepared:error])
    {
        return NO;
    }

    const char *dbpath = [_dbPath UTF8String]; 
    if (sqlite3_open(dbpath, &_contactDb) != SQLITE_OK &&
        error != nil)
    {
        *error = [[[NSError alloc] initWithDomain:@"ContactsManager" code:1000 userInfo:nil] autorelease];
        return NO;
    }

   NSLog(@"opened");

    return YES;
}

- (BOOL)ensureDatabasePrepared: (NSError **)error
{
    // already prepared
    if ((_dbPath != nil) &&
        ([[NSFileManager defaultManager] fileExistsAtPath:_dbPath]))
    {
        return YES;
    }

    // db in main bundle - cant edit.  copy to library if !exist
    NSString *dbTemplatePath = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"db"];
    NSLog(@"%@", dbTemplatePath);

    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    _dbPath = [libraryPath stringByAppendingPathComponent:@"contacts.db"];

    NSLog(@"dbPath: %@", _dbPath);

    // copy db from template to library
    if (![[NSFileManager defaultManager] fileExistsAtPath:_dbPath])
    {
        NSLog(@"db not exists");
        NSError *error = nil;
        if (![[NSFileManager defaultManager] copyItemAtPath:dbTemplatePath toPath:_dbPath error:&error])
        {
            return NO;
        }

        NSLog(@"copied");
    }    

    return YES;    
}

答案 1 :(得分:0)

如果您只是从您发布的代码与数据库进行交互,那么您将缺少sqlite3_close。很可能这些更改没有刷新到磁盘上