简体   繁体   English

从sqlite数据库中删除记录

[英]Delete records from sqlite database

I am new to ios Development. 我是ios Development的新手。 Can you help me to delete a record from a table. 你能帮我从表中删除一条记录吗? Database and query seems fine. 数据库和查询似乎很好。 But I dont know why its not deleteing the records. 但我不知道为什么它不删除记录。 I Can see the nslog "profile deleted" in my console. 我可以在控制台中看到nslog“profile deleted”。 Thanks in advance. 提前致谢。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    self.str_databasePath = [documentsDirectory stringByAppendingPathComponent:@"MY_database.sqlite"];

    sqlite3 *database = nil;

    if (sqlite3_open([self.str_databasePath UTF8String], &database) == SQLITE_OK)
    {
        NSLog(@"database opened : %@", profileType);
        const char* sqlStatement;
        if([profilerType isEqualToString:@"personal"]){
            sqlStatement = "DELETE FROM TABLE1 where profile_type = 'OWN_PERSONAL'";
        }else if([profilerType isEqualToString:@"corporate"]){
            sqlStatement = "DELETE FROM TABLE2 where profile_type = 'BANK_PROFILE'";  
        }
        sqlite3_stmt *statement;

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK)
        {
            NSLog(@"profile deleted ");
            return YES;
        }else{

            NSAssert1(0,@"Error: Failed to prepare statement with message %s '.", sqlite3_errmsg(database));
        }


        // Finalize and close database.
        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
     return NO;

As HeikoG said, it's much easier to use Core Data. 正如HeikoG所说,使用Core Data要容易得多。 Core Data is basically an SQLite db, but it's much easier to use. Core Data基本上是一个SQLite数据库,但它更容易使用。 Have a look at this tutorial: http://www.raywenderlich.com/934/core-data-tutorial-getting-started 看看这个教程: http//www.raywenderlich.com/934/core-data-tutorial-getting-started

You will probably save time if you use that instead of using SQL directly, even if you have to re-write your current code. 如果使用它而不是直接使用SQL,即使必须重新编写当前代码,也可以节省时间。

It's not deleting records because you're only preparing the query, never executing it. 它不会删除记录,因为您只是准备查询,从不执行它。

To execute a prepared query, you must call sqlite3_step 要执行准备好的查询,必须调用sqlite3_step

Alternatively, you can use sqlite3_exec which is a convenience function that performs prepare, step and finalize. 或者,您可以使用sqlite3_exec ,它是一个执行准备,步骤和完成的便捷函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM