1
-(IBAction)btnAddToFavorite:(id)sender
{
    [self insertDataToFavourites:[[tempDict objectForKey:@"pageid"]intValue]:[tempDict objectForKey:@"desc"]];
}

-(void)insertDataToFavourites:(int)pageid :(NSString *)description
{
    sqlite3_stmt *insertStatement = nil;
    NSString *sql;
    int returnvalue;
        sql = [NSString stringWithFormat:@"insert into AddFavorite (Id,Description) VALUES (?,?)"];

    returnvalue = sqlite3_prepare_v2(database, [sql UTF8String], -1, &insertStatement, NULL);

    NSLog(@"\nFavorite ID is:--> %d &\nDescription is:--> %@",[[tempDict valueForKey:@"pageid"] intValue] ,[tempDict valueForKey:@"desc"]);

    if (returnvalue == 1){
        NSAssert1 (0,@"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
    }
    sqlite3_bind_text(insertStatement, 1,[[tempDict objectForKey:@"pageid"] UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(insertStatement, 2,[[tempDict objectForKey:@"desc"] UTF8String], -1, SQLITE_TRANSIENT);

    if (SQLITE_DONE != sqlite3_step(insertStatement)){
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    }
    else{
        sqlite3_reset(insertStatement);
    }

    sqlite3_finalize(insertStatement);
}

这是将数据插入数据库的代码。当我使用选择查询检查数据库时,它显示这样的数据。

在此处输入图像描述

谁能告诉我错误在哪里?

谢谢。

4

1 回答 1

1

尝试使用 pageid 方法变量而不是您的 dict,也许 dict 是错误的。另一方面,您插入 id

sqlite3_bind_text(insertStatement, 1,[[tempDict objectForKey:@"pageid"] UTF8String], -1, SQLITE_TRANSIENT);

我认为这可能不正确。

对于测试用例,您可以将 SQLiteManager 作为 sqlstatement 插入

插入 AddFavorite (Id,Description) VALUES (1,'TestDescription');

检查语句是否正确。

如果 id 是数据库中的 int,我将使用此代码插入您的值

-(void)insertDataToFavourites:(int)pageid :(NSString *)description
{
   sqlite3 *database;

   if(sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK) {

      const char *sqlStatement = "INSERT INTO AddFavorite (Id,Description) VALUES (?,?);";

      sqlite3_stmt *compiled_statement;
      if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiled_statement, NULL) == SQLITE_OK)    {

        sqlite3_bind_int(compiled_statement, 1, pageid);
        sqlite3_bind_text(compiled_statement, 2, [description UTF8String] , -1, SQLITE_TRANSIENT);

      }

      if(sqlite3_step(compiled_statement) != SQLITE_DONE ) {
        NSLog( @"Error: %s", sqlite3_errmsg(database) );
      } else {
        NSLog( @"Insert into row id = %lld", sqlite3_last_insert_rowid(database));
      }

      sqlite3_finalize(compiled_statement);
  }

  sqlite3_close(database); 
}
于 2012-08-08T14:20:17.293 回答