Reputation: 413
I drag locationsWOW.sqlite3 file into my project and trying to load it in.The console did't show info about NSLog(@"failed to open database!")
; but show NSLog(@"database open");
And even when I change the name of locationsWOW
to be locations (@"locations" ofType:@"sqlite3"];)
which is not existing ,still the project successfully compiled and my .sqlite database didn't work.Any could help me a beginner.
Here is my code.
-(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;
}
Upvotes: 1
Views: 749
Reputation: 9589
As a beginer just do the following steps in your code
+(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;
}
After when create the Table
+(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);
}
Upvotes: 1