Thursday, 30 April 2015

DataBase ( Using External Class )

SQLite Database ( Using External Class )



Database Demo For Begineer.......



Create SQLite database in iOS ..... & Put in 
Bundle of Application 

-> select Build Phases > Copy Bundle Resources 
    add Your Database in Bundle


-> Open the Build Phases tab, and within 
    Link Binary with Libraries, add the 
    Following framework:

  - libsqlite3.dylib


Note :-  Create DBOperation file with NSObject Class 

        :- Change database name in DBOperation.m file 

        :- In didFinishLaunchingWithOptions  method In 

           AppDelegate.m  file 


            Write ->   [DBOperation checkCreateDB];



1 ) Set Your StoryBoard Which is Given Below :-




2) Write Coding in Different View Controller

    Which is Given Below :


Note :-> First Create DBOperation Class File (NSObject) :

* NSObject Class (For Create Data Base operation Class) :

DBoperation.h :

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface DBOperation : NSObject 
{
}

+(void)OpenDatabase:(NSString*)path;  //Open the Database
//+(void)finalizeStatements;//Closing and do the final statement at application exits
+(void)checkCreateDB;
//+(int) getLastInsertId;
+(BOOL) executeSQL:(NSString *)sqlTmp;
+(NSMutableArray*) selectData:(NSString *)sql;
@end


DBoperation.m :


#import "DBOperation.h"

static sqlite3 *database = nil;
static int conn;
@implementation DBOperation


+(void)checkCreateDB{
    @try {
        NSString *dbPath,*databaseName;
        
        databaseName=@"mydb.sqlite";
        
        NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *docDir = [docPaths objectAtIndex:0];
        dbPath = [docDir stringByAppendingPathComponent:databaseName];
        BOOL success;
        NSFileManager *fm = [NSFileManager defaultManager];
        success=[fm fileExistsAtPath:dbPath];
        if(success)
        {
            [self OpenDatabase:dbPath];
            return;
        }
        NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
        [fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
        [self OpenDatabase:dbPath];

    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception reason]);

    }
}

//Open database
+ (void) OpenDatabase:(NSString*)path
{
@try
{
conn = sqlite3_open([path UTF8String], &database);
if (conn == SQLITE_OK) {
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}
@catch (NSException *e) {
NSLog(@"%@",e); 
}
}



+(NSMutableArray*) selectData:(NSString *)sql
{
    @try 
    {
        if (conn == SQLITE_OK
        {
            sqlite3_stmt *stmt = nil;
            if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK) {
                [NSException raise:@"DatabaseException" format:@"Error while creating statement. '%s'", sqlite3_errmsg(database)];
            }
            NSMutableArray *obj = [[NSMutableArray alloc]init];
            int numResultColumns = 0;
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                numResultColumns = sqlite3_column_count(stmt);
                @autoreleasepool {
                    NSMutableDictionary *tmpObj = [[NSMutableDictionary alloc]init];
                    for(int i = 0; i < numResultColumns; i++){
                        if(sqlite3_column_type(stmt, i) == SQLITE_INTEGER){
                            
                            const char *name = sqlite3_column_name(stmt, i);
                            NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
                            [tmpObj setObject:[NSString stringWithFormat:@"%i",sqlite3_column_int(stmt, i)] forKey:columnName];
                            
                        } else if (sqlite3_column_type(stmt, i) == SQLITE_FLOAT) {
                            
                            const char *name = sqlite3_column_name(stmt, i);
                            NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];

                            [tmpObj setObject:[NSString stringWithFormat:@"%f",sqlite3_column_double(stmt, i)] forKey:columnName];
                        } else if (sqlite3_column_type(stmt, i) == SQLITE_TEXT) {
                            const char *name = sqlite3_column_name(stmt, i);
                            NSString *tmpStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
                            if ( tmpStr == nil) {
                                tmpStr = @"";
                            }
                            NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
                            [tmpObj setObject:tmpStr forKey:columnName];
                            
                        } else if (sqlite3_column_type(stmt, i) == SQLITE_BLOB) {
                            
                        }     
                        else if (sqlite3_column_type(stmt, i) == SQLITE_NULL) {
                            const char *name = sqlite3_column_name(stmt, i);
                            NSString *tmpStr = @"";
                            
                            NSString *columnName = [[NSString alloc]initWithCString:name encoding:NSUTF8StringEncoding];
                            [tmpObj setObject:tmpStr forKey:columnName];
                        }
                        
                    }
                    [obj addObject:tmpObj];
                
                }
            }
            return obj;
        } else {
            return nil;
        }
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception reason]);
        return nil;
    }
 }

+(BOOL) executeSQL:(NSString *)sqlTmp
{
@try {
        if(conn == SQLITE_OK) {     
            
            const char *sqlStmt = [sqlTmp cStringUsingEncoding:NSUTF8StringEncoding];
            sqlite3_stmt *cmp_sqlStmt1;
            int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt1, NULL);
            
            returnValue == SQLITE_OKNSLog(@"\n Inserted \n") :NSLog(@"\n Not Inserted \n");
            
            sqlite3_step(cmp_sqlStmt1);
            sqlite3_finalize(cmp_sqlStmt1);
            
            if (returnValue == SQLITE_OK)
            {
                return TRUE;
            }
        }
        return FALSE;

    }
    @catch (NSException *exception)
    {
        NSLog(@"%@",[exception reason]);
        return NO;
    }
}

@end


* AppDelegate (For pass database ) :

AppDelegate.m :


#import <sqlite3.h>
#import "DBOperation.h"

 :- In didFinishLaunchingWithOptions  method In 

    AppDelegate.m  file 


   Write ->   [DBOperation checkCreateDB];

EX :-  

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [DBOperation checkCreateDB];
    return YES;
}




* ViewController (For Login View Controller) :

ViewController.h :


#import <UIKit/UIKit.h>
#import "DBOperation.h"
#import <sqlite3.h>
#import "SecViewController.h"

@interface ViewController : UIViewController

{
    int n;
}
@property(strong, nonatomic)IBOutlet UITextField *txtusername;

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

@property(strong,nonatomic)SecViewController *secviewobj;

-(IBAction)login:(id)sender;
-(IBAction)registeration:(id)sender;

@end


ViewController.m :


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize txtpassword,txtusername;
@synthesize secviewobj;


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction)login:(id)sender
{
    NSMutableArray *arrDB=[DBOperation selectData:[NSString stringWithFormat:@"Select * from data"]];
    
    for (int i=0; i<arrDB.count; i++)
    {
        NSLog(@"%@",[[arrDB objectAtIndex:i]objectForKey:@"username"]);
        
        if ([txtusername.text isEqualToString:[[arrDB objectAtIndex:i]objectForKey:@"username"]] && [txtpassword.text isEqualToString:[[arrDB objectAtIndex:i]objectForKey:@"password"]])
        {
            
            NSLog(@"User Name Match");
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Congratulation" message:@"You are Login" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
            
            [alert show];
            
            n = 0;
            break;
           
        }
       else
       {
           n = 1;

       }
    }
    
    if (n == 1)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Your Data is Not Correct" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
        
        [alert show];
    }
}

-(IBAction)registeration:(id)sender
{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    secviewobj = [story instantiateViewControllerWithIdentifier:@"SecViewController"];
    
    [self.navigationController pushViewController:secviewobj animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



* ViewController (For Registration View Controller) :

SecViewController.h :


#import <UIKit/UIKit.h>
#import "DBOperation.h"
#import <sqlite3.h>

@interface SecViewController : UIViewController


@property(strong,nonatomic) IBOutlet UITextField *txtname;
@property(strong,nonatomic) IBOutlet UITextField *txtpass;
@property(strong,nonatomic) IBOutlet UITextField *txtconform;
@property(strong,nonatomic) IBOutlet UITextField *txtmob;

-(IBAction)save:(id)sender;
-(IBAction)search:(id)sender;
-(IBAction)update:(id)sender;
-(IBAction)drop:(id)sender;


@end

SecViewController.m :

#import "SecViewController.h"

@interface SecViewController ()

@end

@implementation SecViewController
@synthesize txtmob,txtname,txtpass,txtconform;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.
}

-(IBAction)save:(id)sender
{
    NSMutableArray *arrDB=[DBOperation selectData:[NSString stringWithFormat:@"SELECT username, mob FROM data "]];
    
    NSMutableArray *arrusername = [[NSMutableArray alloc] init];
    NSMutableArray *arrmobile = [[NSMutableArray alloc] init];
    
    [arrusername addObjectsFromArray:[arrDB valueForKey:@"username"]];
    [arrmobile addObjectsFromArray:[arrDB valueForKey:@"mob"]];
    
    
    if ([arrusername containsObject:txtname.text])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Your Username is already Registered" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
        
        [alert show];
    }
    else
    {
    
        if ([arrmobile containsObject:txtmob.text])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Your mobile no. is already Registered" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
            
            [alert show];
        }
        else
            {
                if ([txtpass.text isEqualToString:txtconform.text])
                {
                    [DBOperation executeSQL:[NSString stringWithFormat:@"Insert Into data (username,password,mob) Values ('%@','%@','%@')",txtname.text,txtpass.text,txtmob.text]];

                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Congratulation" message:@"Your Data Saved" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
         
                    [alert show];
         
                    txtname.text = @"";
                    txtpass.text = @"";
                    txtconform.text = @"";
                    txtmob.text = @"";
         
                }
                else
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Password and Conform Password Mismatch" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
        
                    [alert show];
                }
            }
        }
    
}
-(IBAction)search:(id)sender
{
    NSMutableArray *arrDB =[[NSMutableArray alloc]init];
    arrDB=[DBOperation selectData:[NSString stringWithFormat:@"SELECT password, mob FROM data WHERE username=\"%@\"",txtname.text]];
    
    NSString *strpass = [[arrDB objectAtIndex:0]objectForKey:@"password"];
    
    NSLog(@"%@",strpass);
    
    NSString *strmob = [[arrDB objectAtIndex:0]objectForKey:@"mob"];
    
    NSLog(@"%@",strmob);

    
    txtpass.text =strpass;
    
    
    txtmob.text =strmob;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Congratulation" message:@"Your Data Searched" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
    
    [alert show];
    
}
-(IBAction)update:(id)sender
{
    [DBOperation executeSQL:[NSString stringWithFormat:@"update data set password='%@',mob='%@' where username='%@'",txtpass.text,txtmob.text,txtname.text]];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Congratulation" message:@"Your Data Succesfully Updated" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
    
    [alert show];
    
    txtname.text = @"";
    txtpass.text = @"";
    txtconform.text = @"";
    txtmob.text = @"";
    
}
-(IBAction)drop:(id)sender
{
    [DBOperation executeSQL:[NSString stringWithFormat:@"delete from data where username='%@' ",txtname.text]];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Congratulation" message:@"Your Data Delated" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"OK", nil];
    
    [alert show];
    
    txtname.text = @"";
    txtpass.text = @"";
    txtconform.text = @"";
    txtmob.text = @"";
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

No comments:

Post a Comment