2
早上來to'ya!使用sqlite3_exec在Objective-c中完成交易並且沒有預期的效果
我目前正在Objective-c中開發一個iOS應用程序,我有一個本地數據庫,允許用戶通過互聯網進行更新。 數據庫在短短的幾天內可能會發生相當大的變化,因此可能會在數十萬之前(不太可能但仍然)之前減少到幾行。
我正在使用sqlite,並試圖執行事務性刪除,並沒有得到任何錯誤,而運行下面的代碼,但它沒有預期的效果,即應刪除的行不會被刪除!
我已經在db之前和之後運行了select查詢,但總是找到應該被刪除的數據。
下面是代碼
@try {
if(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK){
//Db exists and can be open
sqlite3_exec(db, "BEGIN EXCLUSIVE TRANSACTION", 0, 0, 0);
sqlite3_stmt *stmt;
const char *query = [[NSString stringWithFormat:@"DELETE FROM %@
WHERE ? = '?'", table] UTF8String];
if(sqlite3_prepare_v2(db, query, -1, &stmt, NULL)== SQLITE_OK)
{
//integer i = 0
//PrimaryKey contains k primaryKeys
for(int i=0; i<[primaryKey count]; i++){
//i = j < k
sqlite3_bind_text(stmt, 1, (const char *)[parameters UTF8String]
, [parameters lengthOfBytesUsingEncoding:NSUTF8StringEncoding], SQLITE_STATIC);
sqlite3_bind_text(stmt, 2,
(const char *)[[primaryKey objectAtIndex:i] UTF8String]
, [[primaryKey objectAtIndex:i] lengthOfBytesUsingEncoding:NSUTF8StringEncoding ]
, SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_DONE){
NSLog(@"Delete commit failed. Error %s", sqlite3_errmsg(db));
return NO;
}
if(sqlite3_reset(stmt)!= SQLITE_OK){
NSLog(@"SQL error %s", sqlite3_errmsg(db));
return NO;
}
}
//i = k
}
if(sqlite3_exec(db, "COMMIT TRANSACTION", 0, 0, 0) != SQLITE_OK){
NSLog(@"SQL error %s", sqlite3_errmsg(db));
return NO;
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
NSLog(@"SQL error %s", sqlite3_errmsg(db));
sqlite3_close(db);
return NO;
}
@catch (NSException *exception) {
NSLog(@"%@", [exception reason]);
return NO;
}
從那些更習慣使用SQLite的交易將是非常讚賞的任何幫助或提示。
非常感謝!像魅力一樣工作,輸入%@的列名稱。並在第一個sqlite3_exec上添加了一個檢查。 – Hrafn