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:-
![](https://lh4.googleusercontent.com/-jSb1eweDMes/V2u_wSU2AJI/AAAAAAAAFwU/y9C3cGspoVM83Zpgw8hqIbuL-4LB9G_wgCL0B/w694-h624-no/Screen%2BShot%2B2016-06-23%2Bat%2B4.09.57%2BPM.png)
We have to include a library to save data in SQLite, screenshot of the same is given below:-
![](https://lh5.googleusercontent.com/-jGbXNP8XLmk/V2vH6M9e0cI/AAAAAAAAFx8/hI8Yio0qFps6jK7tBKfm2ZjsTGoFRYvOgCL0B/w665-h624-no/Screen%2BShot%2B2016-06-23%2Bat%2B4.10.20%2BPM.png)
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:-
![](https://lh4.googleusercontent.com/-KDb9h9YQssw/V2vGVuiqoBI/AAAAAAAAFxc/6bzWnb_lJHwAiK_JdhIiEa4VceYCIMq1QCL0B/w343-h624-no/Screen%2BShot%2B2016-06-23%2Bat%2B4.29.13%2BPM.png)
![](https://lh6.googleusercontent.com/-LH36dvNGFQE/V2vGXvR7w2I/AAAAAAAAFxc/WhCW3-xBmvsHjLFfnpeX2BbYM4OqSZgWACL0B/w340-h623-no/Screen%2BShot%2B2016-06-23%2Bat%2B4.31.52%2BPM.png)
You can download the project from link given below:-
0 Comment(s)