2011-11-27 217 views
0

我想從我的數據庫中刪除創建行。但它沒有這樣做,我有得到我的表中複製日期的具體內容,所以我要刪除條目的具體日期和每次添加他們,我建立一個連接從sqlite3數據庫刪除某些行

我的代碼是:

static sqlite3 *database = nil; 
static sqlite3_stmt *deleteStmt = nil; 

- (NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                 NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:@"person.sqlite3"]; 
} 


    NSDate *today = [NSDate date]; 
    NSLog(@"%@", today); 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"MM/dd/yy"]; 

    if (sqlite3_open([[self dataFilePath] UTF8String], &database) 
     != SQLITE_OK) 
    { 
     sqlite3_close(database); 
     NSAssert(0, @"Failed to open database"); 
    } 


    NSString * dateString = [dateFormat stringFromDate:today]; 
    if(deleteStmt == nil) 
    { 
     const char *sql = "delete from SHOPPER where DATE = ?"; 
     if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK) 
      NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database)); 
    } 

    //When binding parameters, index starts from 1 and not zero. 
    sqlite3_bind_text(deleteStmt, 3, [dateString UTF8String],-1, NULL); 

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

    sqlite3_reset(deleteStmt); 

    sqlite3_close(database); 

回答

0

sqlite3_bind_text的第二個參數應該是1,而不是3. 它表示'?'的索引字符在準備好的聲明中,並且 因爲只有一個'?'在delete語句,它必須是1

//When binding parameters, index starts from 1 and not zero. 
sqlite3_bind_text(deleteStmt, 1, [dateString UTF8String], -1, NULL); 

那麼,爲什麼你聲明deleteStmt爲靜態,並創建只有一次? 我認爲它應該爲開放數據庫創建,並且因爲您每次打開 並關閉數據庫,您也應該每次都創建(並確定,不重置) deleteStmt。