I have used this two methods in appdelegate:
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"calender.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"calender.sqlite"];
}
And this two methods for inserting and selecting:
- (void)addNEW
{
NSString *path = [am getDBPath];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"insert into Task (task,buttontag) Values ('%@','%@')",textField.text,btntag];
const char *sql = [querySQL UTF8String];
sqlite3_stmt *searchStatement;
if (sqlite3_prepare_v2(database, sql, -1, &searchStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(searchStatement) == SQLITE_ROW)
{
}
am.task_ID = sqlite3_last_insert_rowid(database);
}
sqlite3_finalize(searchStatement);
}
}
-(void) getselectedtask: (NSString *) btnTag
{
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *path = [app getDBPath];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:@"SELECT * from schedule WHERE buttontag='%@'",btnTag];
const char *sql = [querySQL UTF8String];
sqlite3_stmt *searchStatement;
if (sqlite3_prepare_v2(database, sql, -1, &searchStatement, NULL) == SQLITE_OK)
{
while (sqlite3_step(searchStatement) == SQLITE_ROW)
{
ObjectClass *obj = [[ObjectClass alloc] init];
obj.startingHr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 1)];
NSString *sched_ID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 7)];
}
}
sqlite3_finalize(searchStatement);
}
}
Is the Above code valid???