Database connectivity in iphone Application

Hi,Find here the code how to connect the sqlite database in iphone Application
There are requirement to connect the Database an store the local data Sqlite is the option for the iphone App database,Here is the steps


// Write and call this method in your delegate file
- (void) copyDatabaseIfNeeded 
{
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath]; 
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Database.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:@"Database.sqlite"];
}
// Write and call this method where you want to fetch and store the data.
-(void)GetData
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"Database.sqlite"];
static sqlite3 *database = nil;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char *sql = "Select * from Table"; // Your Querry
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW
{
// Fetch the rows
NSString *temp = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
            }
}
}
    sqlite3_close(database);
}

0 comments:

Post a Comment

Powered by Blogger.
Twitter Delicious Facebook Digg Stumbleupon Favorites More