ios - 打开sqlite数据库

Ash*_*wal 4 sqlite xcode ios

我试图从sqlite数据库中读取数据并将其显示在ios应用程序的表视图中.但由于某种原因,我无法打开sqlite数据库,应用程序崩溃了 - 无法打开数据库.

我使用Firefox sqlite管理器创建了数据库,并将文件复制到Xcode项目中.

这是我的代码 -

-(NSString *)dataFilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return [documentsDir stringByAppendingPathComponent:kFilename];
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用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");
    }
Run Code Online (Sandbox Code Playgroud)

And*_*eas 13

这是我打开数据库的方式.我已经很长时间没有做SQLite了,除了提供我在自己的应用程序中使用的代码之外,我无法给你太多帮助.这是我在我的应用程序中使用的类.

static sqlite3 *database;
static sqlite3_stmt *enableForeignKey;

@implementation DBAdapter

+ (sqlite3 *)sharedInstance {

    if (database == NULL) {
        sqlite3 *newDBconnection;

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, 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;
}
Run Code Online (Sandbox Code Playgroud)