我的iOS sqlite删除方法有什么问题?

时间:2016-07-04 03:20:37

标签: ios objective-c sqlite

我正在为iOS制作一个sqlite。我已成功保存数据并显示,但不删除。 这是我的createTable方法:

- (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");
    }
}

这是我的saveData方法:

-(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);
    }
}

这是我的deleteData方法,它无效:

-(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);
    }
}

返回失败。

1 个答案:

答案 0 :(得分:0)

我认为您需要在查询中的nickename之间放置single quote,因为如果它包含空间,则不会删除记录。像这样更改你的删除语句

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