我将locationsWOW.sqlite3文件拖到我的项目中并尝试加载它。控制台没有显示有关NSLog(@"failed to open database!")
的信息;但是显示NSLog(@"database open");
即使我将locationsWOW
的名称更改为地点(@"locations" ofType:@"sqlite3"];)
这是不存在的,仍然项目成功编译,我的.sqlite数据库不起作用。任何人都可以帮助我初学者。
这是我的代码。
-(id)init{
if (self = [super init]) {
NSString *sqlite3DB = [[NSBundle mainBundle]pathForResource:@"locationsWOW" ofType:@"sqlite3"];
if (sqlite3_open([sqlite3DB UTF8String], &_database) != SQLITE_OK) {
NSLog(@"failed to open database!");
}
}
NSLog(@"database open");
return self;
}
答案 0 :(得分:1)
作为初学者,只需在代码中执行以下步骤
+(NSString *)databasePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *sql_Path=[paths objectAtIndex:0];
NSString *dbPath=[sql_Path stringByAppendingPathComponent:@"locationsWOW.sqlite"];
NSFileManager *fileMgr=[NSFileManager defaultManager];
BOOL success;
NSError *error;
success=[fileMgr fileExistsAtPath:dbPath];
if (!success) {
NSString *path=[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"locationsWOW.sqlite"];
success=[fileMgr copyItemAtPath:path toPath:dbPath error:&error];
}
return dbPath;
}
创建表后
+(void)createTable
{
char *error;
NSString *filePath =[self databasePath];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *strQuery=[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS TableName(id TEXT,name TEXT);"];
sqlite3_exec(database, [strQuery UTF8String], NULL, NULL, &error);
}
else
{
NSAssert(0, @"Table failed to create");
NSLog(@"TableName Table Not Created");
}
sqlite3_close(database);
}