0

我正在制作一个带有嵌入式 SQLite 数据库的 iOS 应用程序。所以我在 SQLite 管理员中创建了我的数据库并将其拖到我的 Xcode 项目中,就像教程中所说的那样。当我尝试打开我的数据库时,我收到此错误:“内存不足”。不知道是 SQLite 错误还是什么,但我的文件非常小,不会出现内存问题。

这是我初始化数据库的代码:

- (id)initWithPath:(NSString *)path {
if (self = [super init]) {
    BOOL success;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"SoundLib_DB.sqlite"];

    if ([fileManager fileExistsAtPath:dbPath] == NO) {
        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"SoundLib_DB" ofType:@"sqlite"];
        [fileManager copyItemAtPath:resourcePath toPath:dbPath error:&error];
    }

    success = [fileManager fileExistsAtPath:dbPath];
    if(!success)
    {
        NSLog(@"Cannot locate database file '%@'.", dbPath);
    }
    sqlite3 *dbConnection;
//Here is when I get the error, at trying to open the DB
    if (sqlite3_open_v2("SoundLib", &dbConnection, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) {
        NSLog(@"[SQLITE] Unable to open database!");
        NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
        return nil;
    }
    database = dbConnection;
}
return self;

}

4

2 回答 2

5

错误可能是因为您需要将 databasepath 作为UTF8String. 我看到你正在传递“SoundLib”。你不能那样直接通过。

 if (sqlite3_open([dbPath UTF8String], &databaseHandle) == SQLITE_OK)
{
   //dbPath is your full database path you getting above
}

PS 也有dbpath作为const char

const char *dbpath
于 2013-01-23T16:21:22.997 回答
3

更改您的打开过程,使其看起来像这样......它适用于我;)我想你的主要错误是你忘记了 UTF8String ......

sqlite3 *database;
int result = sqlite3_open([dbPath UTF8String], &database);
if (result != SQLITE_OK) {
    sqlite3_close(database);
    NSLog(@"Error opening databse");
    return;
}
于 2013-01-23T16:25:21.410 回答