我在tableview中使用SQLite数据库加载了一些数据,格式为1)某些值,2)某些值等等。 1和2是主键,这是我的删除代码,我已经在表格视图的删除功能上滑动了
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self openDB];
NSString *idofTable = [NSString new];
NSScanner *scanner = [[NSScanner alloc] initWithString:[self.tableLogView cellForRowAtIndexPath:indexPath].textLabel.text];
[scanner scanUpToString:@")" intoString:&idofTable];
NSLog(@"id=%@, text=%@", idofTable, [self.tableLogView cellForRowAtIndexPath:indexPath].textLabel.text);
if(editingStyle==UITableViewCellEditingStyleDelete)
{
char *error;
NSString *sql = [NSString stringWithFormat:@"DELETE FROM History WHERE 'id' = '%@'", idofTable];
NSLog(@"%@",sql);
if(sqlite3_exec(db, [sql UTF8String], NULL, NULL,&error)!=SQLITE_OK)
{
sqlite3_close(db);
NSAssert(0,@"Could not create table");
}
else
{
NSLog(@"Data Deleted");
sqlite3_exec(db, "COMMIT", NULL, NULL, &error);
}
}
[tableLogView reloadData];
}
日志“已删除数据”已打印,但数据未在数据库或tableview中删除。任何帮助赞赏。我不知道错误发生在哪里,查询似乎是正确的。
答案 0 :(得分:1)
试试这个
if(editingStyle==UITableViewCellEditingStyleDelete)
{
NSString *dbFilePath =[DBclass getDBPath];
sqlite3_stmt *deleteStmt = nil;
if(sqlite3_open([dbFilePath UTF8String], &database)==SQLITE_OK)
{
NSString *deleteString=[NSString stringWithFormat:@"delete from table where ID =%d",idValue];
const char *sql =[deleteString UTF8String];
if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating delete view statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE != sqlite3_step(deleteStmt))
NSAssert1(0, @"Error while deleting data. '%s'", sqlite3_errmsg(database));
else
NSLog(@"Success in deleting the medicine.");
sqlite3_close(database);
}
}
[tableLogView reloadData];
答案 1 :(得分:1)
您尚未最终确定或关闭数据库。
sqlite3_finalize(stmt);
sqlite3_close(DB);
答案 2 :(得分:0)
这是删除行的正确方法:
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
NSString *sql = [NSString stringWithFormat:@"DELETE FROM History WHERE 'id' = '%@'", idofTable];
const char *del_stmt = [sql UTF8String];
sqlite3_prepare_v2(contactDB, del_stmt, -1, & deleteStmt, NULL);
if (sqlite3_step(deleteStmt) == SQLITE_DONE)
{
NSLog(@"Data Deleted");
sqlite3_exec(db, "COMMIT", NULL, NULL, &error);
}else {
NSLog( @"Error: %s", sqlite3_errmsg(database) );
}
sqlite3_finalize(deleteStmt);
sqlite3_close(contactDB);
}