gpt4 book ai didi

ios - 无法在文档目录的子文件夹中创建 sqlite 数据库

转载 作者:行者123 更新时间:2023-12-01 17:41:56 24 4
gpt4 key购买 nike

我正在尝试在我的 iOS 应用程序中使用 Sqlite3 创建数据库。如果我在文档目录的子文件夹中创建数据库,则它不会创建数据库,而是无法打开或创建数据库。如果我不在子文件夹中创建数据库,而是直接在文档目录中创建它。它正在正确创建它。

它给出的路径为databasePath:“/var/mobile/Containers/Data/Application/986037DB-6FA0-4066-9977-C5D7A075C5E7/Documents/MailFolder/INBOX.db”但它失败了 -> if (sqlite3_open(dbpath, &database) == SQLITE_OK) –下面是我在子文件夹中创建数据库的代码。有人可以纠正我这里出了什么问题吗?

- (BOOL) createFolderMailDB :(NSString *) dbName {
NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//docsDir =[[dirPaths objectAtIndex:0] stringByAppendingPathComponent:@"MailFolder"];
NSString *documentsPath = [dirPaths objectAtIndex:0];
docsDir = [documentsPath stringByAppendingPathComponent:@"/MailFolder"];

//docsDir = dirPaths[0];
// Build the path to the database file
NSMutableString *finalDBPath = [[NSMutableString alloc]init];
[finalDBPath appendString:dbName];
[finalDBPath appendString:@".db"];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: finalDBPath]];

NSLog(@"databasePath: %@", databasePath);

BOOL isSuccess = YES;

NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists MailFolderDBTable (emailid text, foldername text, messagedata text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(@"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(@"Failed to open/create database");
}
}

return isSuccess;
}

最佳答案

放置此数据库的文件夹必须存在,否则尝试在其中创建数据库将会失败。因此,在继续创建数据库之前创建该文件夹:

NSString *documentsPath  = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *databaseFolder = [documentsPath stringByAppendingPathComponent:@"MailFolder"];
NSFileManager *filemgr = [NSFileManager defaultManager];

if (![filemgr fileExistsAtPath:databaseFolder]) {
NSError *error;
if (![filemgr createDirectoryAtPath:databaseFolder withIntermediateDirectories:FALSE attributes:nil error:&error]) {
NSLog(@"Error creating %@: %@", databaseFolder, error);
}
}

NSString *databasePath = [[databaseFolder stringByAppendingPathComponent:dbName] stringByAppendingPathExtension:@"db"];

if (![filemgr fileExistsAtPath:databasePath]) {
// database creation logic
}

关于ios - 无法在文档目录的子文件夹中创建 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212461/

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