2 daffodilgirl DaffodilGirl 于 2013.01.24 10:46 提问

打开SQlite数据库的时候报错

用嵌入SQLite数据库开发ios应用,我把数据库放到SQlite管理员,然后拖到Xcode工程中。但是当我打开DB的时候,报错 out of memory ,不知道是不是SQlite的bug,因为我的文件很小,应该不会报出内存问题。

初始化数据库的代码:

- (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;
}

2个回答

g989_1314125
g989_1314125   2013.01.24 13:13
已采纳

报错可能是由于数据库路径传递为UTF8String,我看见你传递"SoundLib",不能这样直接传递。

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

P.S.dbpath作为const char

const char *dbpath
xinyoulingxi1_tong
xinyoulingxi1_tong   2013.01.24 13:38

应该是你忘了 UTF8String

sqlite3 *database;
int result = sqlite3_open([dbPath UTF8String], &database);
if (result != SQLITE_OK) {
    sqlite3_close(database);
    NSLog(@"Error opening databse");
    return;
}
DaffodilGirl
DaffodilGirl 你的答案也正确,不过另外先回答的,谢谢
接近 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!