gpt4 book ai didi

xcode - xcode sqlite3删除数据库错误

转载 作者:行者123 更新时间:2023-12-03 18:39:06 26 4
gpt4 key购买 nike

我正在为我的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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com