2009-09-08

How to create a database connection in iPhone application

// Get the database file path
- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

- (void)loadView {
   
    // The query is for the table name 'UserAuth'
    query = @"SELECT * FROM UserAuth";
   
    NSString finalTry=[self dataFilePath];
   
   // Open the database if it already exist or create the database 
    if (sqlite3_open([finalTry UTF8String], &database)!= SQLITE_OK) {
        sqlite3_close(database);
        NSAssert(0, @"Failed to open database");
    }
   
    else{
       
        if (sqlite3_prepare_v2( database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
           
            while (sqlite3_step(statement) == SQLITE_ROW) {
               
                //your code here

            }
           
            sqlite3_finalize(statement);
        }
       
    }   
   
    //Close the Database
    sqlite3_close(database);
}

No comments: