NoviceDeveloper
NoviceDeveloper

Reputation: 225

How to delete data from sqlite

I have created a table with three entries name,adress and phone no. Now i want to delete data based on the name i type in the name text field. I successfully doing this but the problem is that if I type a name which is not in my database label still show 'contact deleted '... Here is my code

   -(void)deleteContact{
      const char *dbPath=[databasePath UTF8String];
      sqlite3_stmt *statement;
      if (sqlite3_open(dbPath, &contactDB)==SQLITE_OK)
          {

    NSString *querySQL=[NSString stringWithFormat:@"delete from 
                contacts where name=\"%@\"",name.text];
    const char *query_stmt=[querySQL UTF8String];
        sqlite3_prepare_v2(contactDB, query_stmt,-1,&statement, NULL);
        (sqlite3_step(statement)==SQLITE_OK); 

            status.text=@"Contact Deleted"; 
    name.text=@"";
    address.text=@"";
    phone.text=@"";

        sqlite3_finalize(statement);

    }
sqlite3_close(contactDB);

[name resignFirstResponder];
}

Upvotes: 1

Views: 1501

Answers (2)

Valeriy Van
Valeriy Van

Reputation: 1865

Delete is OK even if there is nothing to delete. If you need to know if there is anything to delete you should check this.

NSString *sql = [NSString stringWithFormat:@"select count (*) from contacts where name=\"%@\"", name.text];
sqlite3_stmt *stmt;
int res = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
if (res != SQLITE_OK) {
    NSLog(@"sqlite3_prepare_v2() failed");
    return;
}
int count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
    count = sqlite3_column_int(stmt, 0);
}
sqlite3_finalize(stmt);

if (count == 0) {
    // nothing to delete, do whatever you like
} else {
    // do real delete
    // your code for that seems to be OK
}

Upvotes: 2

Valeriy Van
Valeriy Van

Reputation: 1865

delete from YourTable where name = "NameToDelete"
will delete all records with field name equal to NameToDelete from table YourTable.

Upvotes: 2

Related Questions