OStack程序员社区-中国程序员成长平台

标题: objective-c - 使用 sqlite3_exec 在 Objective-c 中进行事务并没有达到预期的效果 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 17:09
标题: objective-c - 使用 sqlite3_exec 在 Objective-c 中进行事务并没有达到预期的效果

早上好!

我目前正在使用 Objective-c 开发一个 iOS 应用程序,并且我有一个本地数据库,我允许用户通过互联网进行更新。 数据库可以在短短几天内发生相当大的变化,因此可以全部减少到几行,而之前有数十万行(不太可能但仍然如此)。

我正在使用 sqlite 并尝试执行事务性删除,并且在运行以下代码时没有出现任何错误,但它没有达到预期的效果,即应该删除的行没有被删除!

我之前、之后和之后都在数据库上运行过选择查询,但总是找到应该删除的数据。

这里是代码

@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 中使用事务的人提供的任何帮助或提示。



Best Answer-推荐答案


你没有检查结果

sqlite3_exec(db, "BEGIN EXCLUSIVE TRANSACTION", 0, 0, 0);

中有多余的引号
WHERE ? = '?'

sqlite3_bind_text

不需要这些引号

我怀疑您正在尝试为参数 1 绑定(bind)列名。您不能在 SQLite 中执行此操作。 sqlite3_prepare_v2 需要知道列名;您的查询只是将列名与参数 2 进行比较。

关于objective-c - 使用 sqlite3_exec 在 Objective-c 中进行事务并没有达到预期的效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12937288/






欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4