ios – 打开sqlite数据库
发布时间:2020-12-14 18:56:15 所属栏目:百科 来源:网络整理
导读:我试图从sqlite数据库中读取数据并将其显示在ios应用程序的表视图中.但由于某种原因,我无法打开sqlite数据库,应用程序崩溃了 – 无法打开数据库. 我使用Firefox sqlite管理器创建了数据库,并将文件复制到Xcode项目中. 这是我的代码 – -(NSString *)dataFile
|
我试图从sqlite数据库中读取数据并将其显示在ios应用程序的表视图中.但由于某种原因,我无法打开sqlite数据库,应用程序崩溃了 – 无法打开数据库.
我使用Firefox sqlite管理器创建了数据库,并将文件复制到Xcode项目中. 这是我的代码 – -(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:kFilename];
}
我正在尝试使用viewDidLoad中的sqlite3_open_v2命令打开数据库 sqlite3 *database;
if (sqlite3_open_v2([[self dataFilePath] UTF8String],&database,SQLITE_OPEN_READWRITE,NULL) != SQLITE_OK) {
sqlite3_close(database); // not sure you need to close if the open failed
NSAssert(0,@"Failed to open database");
}
解决方法
这是我打开数据库的方式.我已经很长时间没有做SQLite了,除了提供我在自己的应用程序中使用的代码之外,我无法给你太多帮助.这是我在我的应用程序中使用的类.
static sqlite3 *database;
static sqlite3_stmt *enableForeignKey;
@implementation DBAdapter
+ (sqlite3 *)sharedInstance {
if (database == NULL) {
sqlite3 *newDBconnection;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"klb_db.sqlite"];
if (sqlite3_open([path UTF8String],&newDBconnection) == SQLITE_OK) {
//NSLog(@"Database Successfully Opened :)");
database = newDBconnection;
if (sqlite3_prepare_v2(database,"PRAGMA foreign_keys = ON",-1,&enableForeignKey,NULL) != SQLITE_OK) {
NSLog(@"ERROR IN PRAGMA!");
}
sqlite3_finalize(enableForeignKey);
} else {
NSLog(@"Error in opening database :(");
database = NULL;
}
}
return database;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
