将表添加到现有数据库IOS sqlite

时间:2014-02-24 11:36:36

标签: ios iphone objective-c database sqlite

我在iOS应用中使用SQLite DB。在我的屏幕1中,我成功地创建了一个数据库,一个表,插入并从中检索。

但是,当我尝试在同一个数据库中创建一个表并插入值时,从屏幕2开始,我无法进行。

这是我正在使用的代码。

    -(void) createDB{
    NSString *docsDir;
    NSArray *dirPaths;

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = dirPaths[0];

    // Build the path to the database file
    _databasePath = [[NSString alloc]
                     initWithString: [docsDir stringByAppendingPathComponent:
                                      @"coning.db"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: _databasePath ] == NO)
    {
        const char *dbpath = [_databasePath UTF8String];

        if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt =
            "CREATE TABLE IF NOT EXISTS order (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT UNIQUE , ADDRESS TEXT UNIQUE, PHONE TEXT UNIQUE)";

            if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                NSLog(@"Failed to create table");
            }
            sqlite3_close(_contactDB);
        } else {
            NSLog(@"Failed to open/create database");
        }
    }



}
- (void)saveData {
    sqlite3_stmt    *statement;
    const char *dbpath = [_databasePath UTF8String];

    if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
    {

        NSString *insertSQL = [NSString stringWithFormat:
                               @"INSERT OR REPLACE INTO order (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")",
                               @"name", @"address", @"phone"];

        const char *insert_stmt = [insertSQL UTF8String];
        sqlite3_prepare_v2(_contactDB, insert_stmt,
                           -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_DONE)
        {
            NSLog(@"added");
        } else {
           NSLog(@"Failed to add contact");
        }
        sqlite3_finalize(statement);
        sqlite3_close(_contactDB);
    }
}

我一直在使用相同的代码在表1中添加条目,但是当我创建表2时,它表示“无法添加联系人”。有人可以建议我可能出错的地方吗?

另外,我想在表2中将表1的PK作为FK。

1 个答案:

答案 0 :(得分:2)

您可以使用sqlite3_exec()方法代替sqlite3_step()。

sqlite3_exec()将执行您提供的任何查询。

我相信,这肯定对你有帮助。

 -(BOOL)createNewTableInExistingDb
  {

       NSArray *array=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *filePath=[array objectAtIndex:0];

       filePath =[filePath stringByAppendingPathComponent:@"database.db"];

       NSFileManager *manager=[NSFileManager defaultManager];

       BOOL success = NO;
      if ([manager fileExistsAtPath:filePath]) 
      {
         success =YES;
      }
      if (!success) 
       {
          NSString *path2=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database.db"];
          success =[manager copyItemAtPath:path2 toPath:filePath error:nil];
 }
    createStmt = nil;
    NSString *tableName=@"SecondTable";
   if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
     if (createStmt == nil) {

         NSString *query=[NSString stringWithFormat:@"create table %@(RegNo integer, name text)",tableName];

    if (sqlite3_prepare_v2(database, [query UTF8String], -1, &createStmt, NULL) != SQLITE_OK) {
        return NO;
    }
    sqlite3_exec(database, [query UTF8String], NULL, NULL, NULL);
    return YES;
}
}
return YES;
}
相关问题