SQLite in iPhone

Introduction

In this article I will create a contacts book. For this we use three text fields for "name,address,phone" entity and two buttons, a "save" button to save contact details in the phone book and a "find" button to search contacts by name.

To understand better follow these steps.

Step 1

Open Xcode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now select "Single View Application" and click on "Next".

Step 4

Now provide your Product Name and Company Identifier then click on "Next".

Step 5

Select the location where you want to save your project and click on "Create".

Step 6

Initially here we add the library for SQLite. We do that in the same way as we do for adding a framework.

framework-in-iPhone.png

Now we write the code:

AppDelegate.h

//

// databaseAppDelegate.h

// Sqlite_Database

//

// Created by Sachin Bhardwaj on 15/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@class databaseViewController;

@interface databaseAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) databaseViewController *viewController;

@end


AppDelegate.m

//

// databaseAppDelegate.m

// Sqlite_Database

//

// Created by Sachin Bhardwaj on 15/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "databaseAppDelegate.h"

#import "databaseViewController.h"

@implementation databaseAppDelegate

- (void)dealloc

{

[_window release];

[_viewController release];

[super dealloc];

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

// Override point for customization after application launch.

self.viewController = [[[databaseViewController alloc] initWithNibName:@"databaseViewController" bundle:nil] autorelease];

self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];

return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application{

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication *)application

{

// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

- (void)applicationWillEnterForeground:(UIApplication *)application

{

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application

{

// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}


- (void)applicationWillTerminate:(UIApplication *)application

{

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}

@end

ViewController.h

//

// databaseViewController.h

// Sqlite_Database

//

// Created by Sachin Bhardwaj on 15/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <sqlite3.h>

@interface databaseViewController : UIViewController

@property (nonatomic) sqlite3 *contactDB;

@property (strong,nonatomic) NSString *databasePath;

@property (strong,nonatomic) IBOutlet UITextField *name;

@property (strong,nonatomic) IBOutlet UITextField *address;

@property (strong,nonatomic) IBOutlet UILabel *status;

@property (strong,nonatomic) IBOutlet UITextField *phone;

-(IBAction)saveData;

-(IBAction)findContact;

@end

ViewController.m

//

// databaseViewController.m

// Sqlite_Database

//

// Created by Sachin Bhardwaj on 15/01/13.

// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.

//

#import "databaseViewController.h"

@interface databaseViewController ()

@end

@implementation databaseViewController

@synthesize name,address,phone,status,contactDB,databasePath;

-(IBAction)saveData

{

sqlite3_stmt *statement;

const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

{

NSString *insertSQL = [NSString stringWithFormat:

@"INSERT INTO CONTACTS (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")",

name.text, address.text, phone.text];

const char *insert_stmt = [insertSQL UTF8String];

sqlite3_prepare_v2(contactDB, insert_stmt,

-1, &statement, NULL);

if (sqlite3_step(statement) == SQLITE_DONE)

{

status.text = @"Contact added";

name.text = @"";

address.text = @"";

phone.text = @"";

} else {

status.text = @"Failed to add contact";

}

sqlite3_finalize(statement);

sqlite3_close(contactDB);

}

}

-(IBAction)findContact

{

const char *dbpath = [databasePath UTF8String];

sqlite3_stmt *statement;

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

{

NSString *querySQL = [NSString stringWithFormat:

@"SELECT address, phone FROM contacts WHERE name=\"%@\"",

name.text];

const char *query_stmt = [querySQL UTF8String];

if (sqlite3_prepare_v2(contactDB,

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";

} else {

status.text = @"Match not found";

address.text = @"";

phone.text = @"";

}

sqlite3_finalize(statement);

}

sqlite3_close(contactDB);

}

}

- (void)viewDidLoad

{

[super viewDidLoad];

NSString *docsDir;

NSArray *dirPaths;

// Get the documents directory

dirPaths = NSSearchPathForDirectoriesInDomains(

NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

// Build the path to the database file

databasePath = [[NSString alloc]

initWithString: [docsDir stringByAppendingPathComponent:

@"contacts.db"]];

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)

{

const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == 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(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)

{

status.text = @"Failed to create table";

}

sqlite3_close(contactDB);

} else {

status.text = @"Failed to open/create database";

}

}

}

//- (void)viewDidUnload

//{

// [super viewDidUnload];

// // Release any retained subviews of the main view.

// // e.g. self.myOutlet = nil;

// self.name = nil;

// self.address = nil;

// self.phone = nil;

// self.status = nil;

//

//}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

ViewController.Xib

xib-file-in-iPhone.png

Step 7

Now select the iPhone platform to see output in the Simulator.

Output:

Output1 in iPhone:

Output1-in-iPhone.png

Output2 in iPhone:

Output2-in-iPhone.png

To save the data we click on the "Save" button.

Output3 in iPhone:

Output3-in-iPhone.png

Massage displayed in the label:

Output4 in iPhone:

Output4-in-iPhone.png

Here we add a new contact's information. 

Output5 in iPhone:

Output5-in-iPhone.png

To find the information of a person whose record was perviously saved, we enter the name of the person and click on the "Find" button. 

Output6 in iPhone:

Output6-in-iPhone.png

Here the message is displayed in the label.


Similar Articles