Kevin Science Kevin Science - 5 months ago 15
iOS Question

What's wrong with my iOS sqlite delete method?

I am making a sqlite for iOS. I have succeeded to save data and present, but not delete.
This is my createTable Method:

- (void) createTable: (NSString *) tableName
withField1: (NSString *) field1
withField2: (NSString *) field2
withField3: (NSString *) field3
withField4: (NSString *) field4{
char *err;
NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' "
"TEXT PRIMARY KEY, '%@' TEXT, '%@' TEXT, '%@' TEXT);", tableName, field1,field2,field3,field4];

if(sqlite3_exec(db,[sql UTF8String], NULL,NULL, &err) != SQLITE_OK) {
sqlite3_close(db);
NSAssert(0, @"Could not create table");
} else {
NSLog(@"table created");
}
}


This is my saveData method:

-(void) saveNewData :(NSString*)nickname :(NSString*)url :(NSString*)uid :(NSString*)pswd{


sqlite3_stmt *statement;

if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSString *sql =[NSString stringWithFormat:@"INSERT INTO accountListDB ('nickname', 'url', 'uid', 'pswd') VALUES ('%@', '%@', '%@', '%@')", nickname, url, uid, pswd];

const char *insert_stmt = [sql UTF8String];
sqlite3_prepare_v2(db, insert_stmt, -1, &statement, NULL);

if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"data added");
}else{
NSLog(@"failed to added");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}


This is my deleteData method, which is not working:

-(void) deleteData:(NSString*)nickname :(NSString*)url :(NSString*)uid :(NSString*)pswd{
sqlite3_stmt *statement;

if (sqlite3_open([[self filePath] UTF8String], &db) == SQLITE_OK) {
NSString *sql =[NSString stringWithFormat:@"DELETE FROM accountListDB WHERE nickname = %@", nickname];

const char *delete_stmt = [sql UTF8String];
sqlite3_prepare_v2(db, delete_stmt, -1, &statement, NULL);

if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"data deleted");
}else{
NSLog(@"failed to delete");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}


It returns failed to delete.

Answer

I think you need to put single quote between your nickename in the query because if it contain space inside that it will not delete the records. Change your delete statement like this

 NSString *sql = [NSString stringWithFormat:@"DELETE FROM accountListDB WHERE nickname = '%@'", nickname];