Nazia Jan
Nazia Jan

Reputation: 783

How to delete all the contents from SQLite table in an iOS app

I want to delete all the rows from the table in my iPhone app. I am using following code but it is not deleting the data:

+(void)emptyData:(NSString*)dbPath{

    NSString *query = @"delete from survey_question_responses";
    const char *sqlStatement = [query UTF8String];
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

   // Loop through the results and add them to the feeds array
     while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
      // Read the data from the result row
        NSLog(@"result is here");
      }

       // Release the compiled statement from memory
      sqlite3_finalize(compiledStatement);
     }
     }

Upvotes: 1

Views: 5731

Answers (2)

Super Xtreem
Super Xtreem

Reputation: 187

Get the path of the DB:

NSString*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString*documentDirectory=[paths objectAtIndex:0];

NSSting*dBPath=[documentDirectory stringByAppendingPathComponent:@"dB.sql"];

Open the DB:

if(sqlite3_open([dBPath UTF8String], &database) == SQLITE_OK){

    NSString*query=[NSString stringWithFormat:@"DELETE from tablename"];
}

Execute the query statement:

if(sqlite3_exec(database, [query UTF8String],NULL, NULL, NULL) == SQLITE_OK){            
   NSLog(@"Delete Query Success);

}
else{

     NSLog(@"Delete Query Failed);}

      sqlite3_close(database);

}

Hope this helps..

Upvotes: 3

Minkle Garg
Minkle Garg

Reputation: 751

NSString *query1 = [NSString stringWithFormat:@"DELETE from TableName"];
[[DBManager sharedDatabase]executeQuery:query1];

where

-(void)executeQuery:(NSString*)_query
{
    const char *sql = [_query cStringUsingEncoding:NSUTF8StringEncoding];
    sqlite3_stmt *statement = nil;

    if(sqlite3_prepare_v2(dataBaseConnection,sql, -1, &statement, NULL)!= SQLITE_OK)
    {
        NSAssert1(0,@"error preparing statement",sqlite3_errmsg(dataBaseConnection));
    }
    else
    {
        sqlite3_step(statement);
    }
    sqlite3_finalize(statement);
}

Upvotes: 5

Related Questions