gpt4 book ai didi

ios - 从 bundle 中调用 sqlite 数据库

转载 作者:行者123 更新时间:2023-11-29 03:27:54 25 4
gpt4 key购买 nike

我正在使用 sqlite 数据库,一切都很顺利。我在表中添加了 4 个条目,然后在我的 xib 文件中添加了 textview。现在我希望该数据应该从放置在项目包中的 sqlite 数据库中获取。但我不知道如何从 bundle 到目录路径调用该数据库。请帮我解决这个问题。

最佳答案

使用此代码:

首先调用此方法,该方法将检查 dbfile 是否存储在文档目录中。如果没有,它会将您的文件写入文档目录。

-(void)openDatabase {

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *dbPath = [self getDBPath];

BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"databasefilename.sqlite"];

success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
error:&error];
if (!success)
NSLog(@"Failed to create writable database file with message '%@'.",
[error localizedDescription]);
}
}

- (NSString *) getDBPath {
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"databasefilename.sqlite"];
}

然后 checkin Appdelegate 或您想要的任何其他类:

if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
NSLog(@"database opened successfully");
}

关于ios - 从 bundle 中调用 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218047/

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