Saturday, October 15, 2011

Create a Table and Insert data to the Table usig Sqlite3 - iPhone



 

    //According to the 'query' create the database  
- (BOOL)executeCreateTableQuery:(NSString*)query
{
    BOOL success = NO;
    MCDatabase *mcDB = [MCDatabase getSharedInstance];  // MCDatabase class has My previous post 
   
    @try {
        char *errorMsg;
        int result = sqlite3_exec([mcDB getOpenedDatabase], [query UTF8String], NULL, NULL, &errorMsg);
        [query release];
        if (result == SQLITE_OK) {
            success = YES;
        }else {
            NSLog(@"eCommerce MCDatabaseConfig-executeQuery: execute failed");
            NSLog(@"%@",query);
        }
    }
    @catch (NSException * e) {
        NSLog(@"eCommerce MCDatabaseConfig-executeQuery: Caught %@: %@", [e name], [e reason]);
    }
    @finally {
        if ([mcDB isDatabaseOpened]) {
            [mcDB closeDatabase];
        }
    }
    return success;
}

 


- (BOOL)createTable
{
    BOOL added = NO;
    BOOL createTable = [self executeTableQuery:@"CREATE TABLE IF NOT EXISTS cache_flags (id INTEGER PRIMARY KEY AUTOINCREMENT,slides INTEGER,speaker_lists STRING)"];
    if (createTable) {
        NSLog(@"-------------------------Databse cache_flags CREATE");
        added = YES;
        NXDatabase *mcDB = [NXDatabase getSharedInstance];   // MCDatabase class has My previous post
       
        @try {
            char *sql = "INSERT OR REPLACE INTO cache_flags(id,slides,speaker_lists) VALUES(?,?,?);";
            sqlite3_stmt *stmt;
            if (sqlite3_prepare_v2([mcDB getOpenedDatabase], sql, -1, &stmt, nil) == SQLITE_OK) {
                sqlite3_bind_int(stmt, 1, 1);
                sqlite3_bind_text(stmt, 3, [(NSString *)[speakersDic valueForKey:@"FIRSTNAME"] UTF8String], -1, NULL);
               
            }
            if (sqlite3_step(stmt) != SQLITE_DONE) {
                NSLog(@"-executeInsertQuery-addNewInvoice: ading new Category failed");
            }else {
                added = YES;
            }
            sqlite3_finalize(stmt);
        }
        @catch (NSException * e) {
            NSLog(@"-executeInsertQuery-addNewInvoice: Caught %@: %@", [e name], [e reason]);
        }
        @finally {
            if ([mcDB isDatabaseOpened]) {
                [mcDB closeDatabase];
                    //[mcDB release];
            }
        }
     
        return added;
    }
    else {
        NSLog(@"-------------------------Database cache_flags Not CREATE");
        return added;
    }
        //[databaseConfig release];
}