2014-10-29 80 views
1

我将locationsWOW.sqlite3文件拖放到我的项目中,并尝试将其加载到中。控制台未显示有关NSLog(@"failed to open database!")的信息;但显示NSLog(@"database open"); 即使当我将locationsWOW的名称更改为位置(@"locations" ofType:@"sqlite3"];) 这是不存在的,仍然项目已成功编译和我的.sqlite数据库不起作用。任何人都可以帮助我一个初学者。如何将my.sqlite3导入到Xcode中的iPhone项目中

这是我的代码。

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

请提供一些更多的澄清你的问题后。 – himan 2014-10-29 10:46:24

回答

1

作为beginer只要做到以下步骤在您的代码

+(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); 

} 
+0

嗨Thx给你的帮助,但仍然没有奏效。我的项目名为'sqlite3Test',以及位于文件夹'sqlite3Test'根目录中的locationsWOW.sqlite文件位置。问题是什么?Thx。 – PeiweiChen 2014-10-30 01:52:05

+0

这不是问题.locationsWOW.sqlite是SQLite数据库名称。 – user3182143 2014-10-30 05:34:57