Ios在sqlite中循环添加值

时间:2014-03-25 09:59:46

标签: ios

嘿,我的代码很简单,我创建了一个带有一列id和消息的sqlite表。 我的sqlite表创建成功。我想在消息列.my代码中插入5个字符串值以插入字符串值

  - (IBAction)addTextToDatabase:(id)sender
  {
     sqlite3_stmt    *statement;
     const char *dbpath = [databasePath UTF8String];

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

        NSString *insertSQL = [NSString stringWithFormat:
                                @"INSERT INTO SAMPLETABLE (MESSAGE) VALUES (\"%@\")",
                                self.textField.text];

          const char *insert_stmt = [insertSQL UTF8String];
          for (int k = 0; k < 5; k++) {
             sqlite3_prepare_v2(myDatabase, insert_stmt,
                                -1, &statement, NULL);


              sqlite3_finalize(statement);
          }
          //  sqlite3_prepare_v2(myDatabase, insert_stmt,
          //                -1, &statement, NULL);
            if (sqlite3_step(statement) == SQLITE_DONE) {
              statusOfAddingToDB = [NSString stringWithFormat:@"Text added -- %@",
             textField.text];
          } else {
            statusOfAddingToDB = @"Failed to add contact";
          }

          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB Status"
           message:statusOfAddingToDB delegate:nil cancelButtonTitle:@"OK"   
            otherButtonTitles:nil];
            [alert show];

      //        sqlite3_finalize(statement);
         sqlite3_close(myDatabase);
     }
    }

但是当我检查我的数据库时,只添加了一个值。请帮助如何实现这个目标?

2 个答案:

答案 0 :(得分:0)

在sqlite3_finalize语句之前在for循环中写入sqlite3_step语句

答案 1 :(得分:0)

您必须运行此声明:

sqlite3_step(compiledStatement)== SQLITE_DONE

每次插入后