简体   繁体   中英

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];
}


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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM