Easy way to access database xcode

Discussion in 'iPhone and iPod touch Apps' started by sunith, Apr 27, 2012.

  1. macrumors newbie

    Joined:
    Apr 27, 2012
    #1
    :apple:To create database:)-
    create database in ViewDidLoad-

    - (void)viewDidLoad {
    NSString *docsDir;
    NSArray *dirPaths;
    dirPaths=NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask,YES);
    docsDir=[dirPaths objectAtIndex:0];
    databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:mad:"contacts.db"]];
    NSFileManager *filemgr=[NSFileManager defaultManager];
    if([filemgr fileExistsAtPath:databasePath]==NO)
    {
    const char *dbpath=[databasePath UTF8String];
    if (sqlite3_open(dbpath,&cDB)==SQLITE_OK)
    {
    char *errMsg;
    const char *sql_stmt="CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
    if (sqlite3_exec(cDB,sql_stmt,NULL,NULL,&errMsg)!=SQLITE_OK)
    {
    status.text=@"Failed to Create Table";
    }
    sqlite3_close(cDB);
    }
    else {
    status.text=@"Failed to Open/Create Data base";
    }

    }
    [filemgr release];
    [super viewDidLoad];
    }

    :apple:To save data to table:-
    -(IBAction) saveData

    {
    sqlite3_stmt *statement;
    const char *dbPath=[databasePath UTF8String];
    if (sqlite3_open(dbPath,&cDB)==SQLITE_OK)
    {
    NSString *insertSQL=[NSString stringWithFormat:mad:"INSERT INTO CONTACTS(name,address,phone) VALUES(\"%@\",\"%@\",\"%@\")",name.text,address.text,phone.text];
    const char *insert_stmt=[insertSQL UTF8String];
    sqlite3_prepare_v2(cDB,insert_stmt,-1,&statement,NULL);
    if(sqlite3_step(statement)==SQLITE_DONE)
    {
    status.text=@"contact added";
    name.text=@"";
    phone.text=@"";
    address.text=@"";
    }
    else {
    status.text=@"failed to add contact";
    }
    sqlite3_finalize(statement);
    sqlite3_close(cDB);
    }



    :apple:To view the saved data:-

    -(IBAction) findContact
    {
    const char *dbpath=[databasePath UTF8String];
    sqlite3_stmt *statement;
    if(sqlite3_open(dbpath,&cDB)==SQLITE_OK)
    {
    NSString *querySQL=[NSString stringWithFormat:mad:"SELECT address,phone FROM contacts WHERE name=\"%@\"",name.text];
    const char *query_stmt=[querySQL UTF8String ];
    if (sqlite3_prepare_v2(cDB,query_stmt,-1,&statement,NULL)==SQLITE_OK)
    {
    if(sqlite3_step(statement)==SQLITE_ROW)
    {
    NSString *addressField=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement,0)];
    address.text=addressField;
    NSString *phoneField=[[NSString alloc]initWithUTF8String:(const char *)sqlite3_column_text(statement,1)];
    phone.text=phoneField;
    status.text=@"Match found";
    [addressField release];
    [phoneField release];
    }
     

Share This Page