sqlite is not updating my database iOS

2019-06-11 01:47发布

问题:

I am trying to update my sqlite database but this code is not working for me. Please help me to find what is wrong with this.

-(BOOL)StoreFavourite:(NSString*)fav :(int)DuaId
{
    NSString* mydbpath=[self pathfinder];

    const char *dbpath=[mydbpath UTF8String];
    if(sqlite3_open(dbpath,&database )==SQLITE_OK)
    {

       NSString *query = [NSString stringWithFormat:@"UPDATE Dua SET 
                       favourite=\'%@\' WHERE dua_id=%d ",fav,DuaId];

       const char *query_statement=[query UTF8String];

       if(sqlite3_prepare_v2(database, query_statement, -1, &statement, NULL)==SQLITE_OK)
       {
          while(sqlite3_step(statement) == SQLITE_DONE)
          {
              return YES;
          }
          sqlite3_finalize(statement);
       }
    }
    return YES;

 }

回答1:

Please check your "mydbpath" by putting NSLog.I think you have given incorrect path.
Also try to use:

NSString *query = [NSString stringWithFormat:@"UPDATE Dua SET favourite='%@' WHERE dua_id=%d ",fav,DuaId];  


回答2:

here are some reason for due to which the sqlite3_prepare_v2 != SQLITE_OK :

1.The table may not present into the database.

2.Wrong query statement .

3.Wrong column name into the query statement.

You can find the exact problem using error statement by putting following in else:

 NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database))


回答3:

please try in following manner

-(BOOL)StoreFavourite:(NSString*)fav :(int)DuaId
{
    sqlite3_stmt *statement=nil;
    NSString *mydbpath=[self pathfinder];
    NSString *query;
    if(sqlite3_open([mydbpath UTF8String],&database) == SQLITE_OK)
    {
        query = [NSString stringWithFormat: @"update Dua set favourite=? where dua_id=?"];

        if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, NULL)
           == SQLITE_OK)
        {
            sqlite3_bind_int(statement, 2, DuaId);
            sqlite3_bind_text(statement, 1, [fav UTF8String], -1, SQLITE_TRANSIENT);

            if(sqlite3_step(statement))
            {
                return YES;
            }
            else
            {
                return NO;
            }

        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);

   return NO;
}