
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
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];
}

-(IBAction) saveData
{
sqlite3_stmt *statement;
const char *dbPath=[databasePath UTF8String];
if (sqlite3_open(dbPath,&cDB)==SQLITE_OK)
{
NSString *insertSQL=[NSString stringWithFormat
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);
}

-(IBAction) findContact
{
const char *dbpath=[databasePath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpath,&cDB)==SQLITE_OK)
{
NSString *querySQL=[NSString stringWithFormat
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
address.text=addressField;
NSString *phoneField=[[NSString alloc]initWithUTF8String
phone.text=phoneField;
status.text=@"Match found";
[addressField release];
[phoneField release];
}