Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to save data in SQLite database in iOS?

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 169
    Comment on it

    Hi Readers,

    In this blog, we will discuss how to save data entered by a user in SQLite database. Before proceeding towards the saving of data into the database you should know how to create a database and tables inside SQLite database.

    Here we are starting with an already created database named as EmpInfo and table named as EmpTable. We are taking only four fields inside the table like name,address,phone and email so we will take only these four fields from a user as input.

     

    Screenshot of storyboard is given below:-

     

     

     

    We have to include a library to save data in SQLite, screenshot of the same is given below:-

     

     

    Next, we have Coding section which I love the most!!!..

    Create 2 new files with a base class as NSObject, one is for making model and another one for managing the database calls.

     

    EmpModel.h
    
    #import <Foundation/Foundation.h>
    
    @interface EmpModel : NSObject
    @property (strong, nonatomic) NSString *empName;
    @property (strong, nonatomic) NSString *empAddress;
    @property (strong, nonatomic) NSString *empPhoneNumber;
    @property (strong, nonatomic) NSString *empEmail;
    @property (assign) NSInteger empId;
    - (id)initWithName:(NSString*)name address:(NSString*)address phone:(NSString*)phone email:(NSString*)email empId:(NSInteger)empid;
    @end
    
    
    
    EmpModel.m
    
    #import "EmpModel.h"
    
    @implementation EmpModel
    - (id)initWithName:(NSString*)name address:(NSString*)address phone:(NSString*)phone email:(NSString*)email empId:(NSInteger)empid {
        if (self == [super init]) {
            self.empId = empid;
            self.empAddress = address;
            self.empName = name;
            self.empPhoneNumber = phone;
            self.empEmail = email;
        }
        return self;
    }
    
    - (NSString *)description {
        return [NSString stringWithFormat:@"%@ \n name: %@ \nemail: %@ \nphone: %@ \naddress: %@",[super description],self.empName, self.empEmail,self.empPhoneNumber,self.empAddress];
    }
    @end
    
    
    

     

    DataBaseManager.h
    
    #import <Foundation/Foundation.h>
    #import <sqlite3.h>
    #import "EmpModel.h"
    
    @interface DataBaseManager : NSObject
    +(id)sharedDatabaseManager;
    
    @property (strong, nonatomic) NSString *databasePath;
    
    - (BOOL)saveEmployeeRecordToDB:(EmpModel*)emp;
    @end
    
    
    
    DataBaseManager.m
    
    #import "DataBaseManager.h"
    
    @implementation DataBaseManager
    static sqlite3 *database = nil;
    static sqlite3_stmt *statement = nil;
    
    + (id)sharedDatabaseManager {
        
        static DataBaseManager *dbManager;
        static dispatch_once_t once;
        
        dispatch_once(&once, ^{
            dbManager = [self new];
            [dbManager createDatabaseFile];
        });
        
        return dbManager;
    }
    
    - (NSString *)databasePath {
        NSString *pathForDocumentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        pathForDocumentDir = [pathForDocumentDir stringByAppendingPathComponent:@"EmpInfo.sqlite"];
        return pathForDocumentDir;
    }
    
    - (void)createDatabaseFile {
        
        NSString *pathForDocumentDir = [self databasePath];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:pathForDocumentDir]) {
            return;
        }
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"EmpInfo" ofType:@"sqlite"];
        NSLog(@"bundle path %@",path);
        
        
        NSLog(@"doc dir path %@",pathForDocumentDir);
        
        NSError *err;
        [[NSFileManager defaultManager] copyItemAtPath:path toPath:pathForDocumentDir error:&err];
        
        if (err) {
            NSLog(@"error while transferring file=> %@",err.localizedDescription);
        } else {
            NSLog(@"db file saved in documents");
        }
    }
    
    
    - (BOOL)saveEmployeeRecordToDB:(EmpModel*)emp {
        
        const char *dbpath = [self.databasePath UTF8String];
        
        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            
            NSString *insertSQL = [NSString stringWithFormat:@"insert into EmpTable (Emp_Name, Emp_Address, Emp_Email, Emp_Phone) values (\"%@\",\"%@\", \"%@\", \"%@\")",[emp empName],[emp empAddress],[emp empEmail],[emp empPhoneNumber]];
            
            const char *insert_stmt = [insertSQL UTF8String];
            
            sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
            
            BOOL success;
            
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
                success = YES;
            }
            else {
                success = NO;
            }
            
            sqlite3_reset(statement);
            
            return success;
        }
        return NO;
    }
    @end

     

     

    ViewController.h
    
    #import <UIKit/UIKit.h>
    #import "DataBaseManager.h"
    
    @interface ViewController : UIViewController
    {
        
        IBOutlet UITextField *txtName;
        IBOutlet UITextField *txtPhone;
        IBOutlet UITextField *txtEmail;
        IBOutlet UITextField *txtAddress;
        
        
    }
    @property (weak, nonatomic) IBOutlet UILabel *lblMessage;
    - (IBAction)btnSaveInDatabase:(id)sender;
    
    @end
    
    
    
    ViewController.m
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (IBAction)btnSaveInDatabase:(id)sender {
        if(txtName.text.length>5 && txtPhone.text.length>5 && txtEmail.text.length>5 && txtAddress.text.length>5)
        {
        
        EmpModel *model = [[EmpModel alloc] init];
        [model setEmpName:txtName.text];
        [model setEmpAddress:txtAddress.text];
        [model setEmpPhoneNumber:txtPhone.text];
        [model setEmpEmail:txtEmail.text];
        
        [[DataBaseManager sharedDatabaseManager] saveEmployeeRecordToDB:model];
            txtName.text=@"";txtAddress.text=@"";txtEmail.text=@"";txtPhone.text=@"";
            _lblMessage.text=@"Record Inserted Successfully";
        }
        else
        {
                    _lblMessage.text=@"";
                    NSString *message=[NSString stringWithFormat:@"%@",@"Please fill all fields"];
                    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"Message" message:message preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *dismiss=[UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
                    }];
                    [alert addAction:dismiss];
                    [self presentViewController:alert  animated:YES completion:nil];
        }
    }
    @end

     

     

    Output:-

     

     

     

    You can download the project from link given below:-

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: