xcode - xcode sqlite3删除数据库错误

标签 xcode caching sqlite

我正在为我的iOS项目使用sqlite3。
登录/注销时,我想重新创建整个数据库。
(我可以执行“从表中删除;”但是有〜10个表,当我需要更多表时,我也必须注意编写删除代码)
所以我搜索删除数据库;但我发现查询无法完成。
据说我必须将其从文件系统中删除;
我的代码是

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *dbPathDB=[appDelegate getDBPath];//dbname.sqlite
//to remove the db
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath =  [documentsDirectory stringByAppendingPathComponent:@"dbname.sqlite"];

//both of them works same if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
if(filePath){
    NSLog(@"it is removed now");
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}

//recreating the db
if (sqlite3_open([dbPathDB UTF8String], &database) == SQLITE_OK) {
    NSLog(@"db is created");

}


当我在设备上进行尝试时,当我第一次登录(尚未删除数据库)时一切正常,当我注销并再次登录时,我在插入数据时遇到错误(但它可以连接到db,该部分有效,错误是关于再次插入同一行)。

而且我停止了该设备,然后再次运行它,并且登录后我没有插入错误,因为数据库很干净。
看起来db文件已删除,但是db处于缓存或类似状态?如何删除和创建相同的数据库,然后正确插入数据?

最佳答案

这个作品:

-(void)removeDB {
    // Check if the SQL database has already been saved to the users phone
    // if not then copy it over
    BOOL success;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    success = [fileManager fileExistsAtPath:[appDelegate getDBPath]];
    if(success) {
        [fileManager removeItemAtPath:[appDelegate getDBPath] error:&error];
        NSLog(@"This one is the error %@",error);
        return;
    }
    //recreating the db
    if (sqlite3_open([[appDelegate getDBPath] UTF8String], &database) == SQLITE_OK) {
        NSLog(@"db is created");
    }
}

关于xcode - xcode sqlite3删除数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11081287/

相关文章:

ios - 使用自动布局在元素之间添加 UI 元素

android - SQLite 连接 :application stops working

android - 在 ListAdapter 将游标数据显示在 ListView 之前编辑游标数据

objective-c - 解析后的 UITableView 委托(delegate)和数据源在单独的类中

iphone - 如何在 Xcode 中创建 iPhone 项目并在项目创建时指定我要使用的 SDK 版本?

php - 使用 Asterisk PHP 脚本匹配电话前缀的最快方法

database - 深度可遍历的 self 中心图的缓存策略

c - SQLite3 : the database was created empty?

iphone - iPhone 上应用程序的内存占用

java - Hibernate的原生查询和缓存机制