从SQLite数据库中删除项目

时间:2013-07-20 09:22:49

标签: iphone ios objective-c sqlite

我有一个应用程序,其中包含可以添加和删除患者的功能。虽然我在删除它时遇到了问题,但工作正常。

这是sql语句:

-(void) deleteTreatmentTypeFromDatabase:(NSString *)deleteid {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"patients.sqlite"];

    sqlite3 *database;

    if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
        const char *sqlStatement = "delete from records WHERE id = ?";
        sqlite3_stmt *compiledStatement;
        NSLog(@"%d", sqlite3_prepare(database, sqlStatement, -1, &compiledStatement, NULL));
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
//            LSAppDelegate *delegate = (LSAppDelegate *)[[UIApplication sharedApplication] delegate];
//            Record *thisRecord = [delegate.records objectAtIndex:index.row];
            sqlite3_bind_text(compiledStatement, 1, [deleteid UTF8String], -1, SQLITE_TRANSIENT);
        }
        if(sqlite3_step(compiledStatement) == SQLITE_DONE) {
            sqlite3_finalize(compiledStatement);
        }
    }
    sqlite3_close(database);
}

当我检查时,它说sql中没有错误,所以我现在很好并且真的卡住了。

请说明是否需要更多代码

提前致谢

2 个答案:

答案 0 :(得分:0)

试试这个,

static sqlite3 *database = nil;

static sqlite3_stmt *deleteStmt = nil;

if(deleteStmt == nil) {
        const char *sql = "delete from Project where ProjectID = ?";
        if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
            NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
    }
    sqlite3_bind_int(deleteStmt, 1, primaryKey);

    if (SQLITE_DONE != sqlite3_step(deleteStmt)) 
        NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));

    sqlite3_reset(deleteStmt);

答案 1 :(得分:-1)

试试这个,

-(void) deleteTreatmentTypeFromDatabase:(NSString *)deleteid {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"patients.sqlite"];

    sqlite3 *database;

    if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
    {
        NSString *query = [NSString stringWithFormat:@"delete from records WHERE id = %@", deleteid];
        sqlite3_stmt *compiledStatement;

        if (sqlite3_prepare_v2(database, [query UTF8String], -1, &compiledStatement, nil) == SQLITE_OK)
        {
          if(sqlite3_step(compiledStatement) == SQLITE_DONE) 
            {
               sqlite3_finalize(compiledStatement);
            }
        }
       sqlite3_close(database);
    }
}