FMDB SQLite
Data base management very huge portion of software development and easy, too. Because of every language is changed means thats upgrade version came in market but this is same from start. FMDB is very easier into all database system.That created from ’SQLite Database’.
Here, we are create database project it’s really somehow matched application form type.You get idea what i want to say by showing this video.
Step 1-Here we are creating single view application.
Step 2-Now, give that product name ‘FMDB demo’.
Step 3- Now, go into ‘Main.storyboard’ and create bellow type platform and give that’s ‘Outlet’ for textfield and create ’Action’ for buttons.
Step 4-Now copy class of FMDB from GitHub and puts into same as bellow picture type.
-FMDB.h
-FMDatabase.h
-FMDatabase.m
-FMResultset.h
-FMResultset.m
-FMDatabaseQueue.h
-FMDatabaseQueue.m
-FMDatabaseAdditions.h
-FMDatabaseAdditions.m
-FMDatabasePool.h
-FMDatabasePool.m
Step 5-Now import class in ‘ViewController.h’
#import <sqlite3.h>
#import "FMDB.h"
#import "FMDatabaseAdditions.h"
now also need to create database see here
{
FMDatabase *db;
}
Here those are not given in picture but you have necessary need to import this.
Step 6-Now we are created table of data that’s for hare we will take
-Id
-Name
-Gender
now write code into ‘[super viewDidLoad]’.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open]) {
return;
}
if (![db tableExists:@"mainuserdetail"])
{
[db executeUpdate:@"CREATE table mainuserdetail(mainUserID text,name text,gender text)"];
[db close];
}
Step 7-Now write code into ‘addButton’..
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open])
{
return;
}
NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO mainuserdetail VALUES ('%@','%@','%@')" ,idField.text,nameField.text, genderField.text ];
NSLog(@"%@",insertQuery);
[db executeUpdate:insertQuery];
[db close];
idField.text = @"";
nameField.text = @"";
genderField.text = @"";
Step 8-Now go into ‘Main.storyboard’ and create bellow type platform. Here ID,Name & Gender they are not taken into ‘TableView’ so our table view size set from click on table view and go into ‘size inspector’ and write in View X=0, Y=96 , Width=320, Height=472.
Step 9-Now Take new file from File ->New ->File. Then give name Class :’TAbleViewController’ where subclass : ‘UIViewController’ and create.
Step 10-One more take file for cell. Then give name class:’MyCell’ and subclass :’UItableViewCell’ and create.
Step 11- Now go into ‘Main.storyboard’ and select controller then go into the ‘Identity Inspector’ and give class ‘TableViewController’.
Step 12- Same as for cell select cell then give that class ‘MyCell’ where give identifier in ‘Attribute Inspector’ name is ‘cell’.
Step 13-After that give ‘Outlet’ of labels into ‘MyCell.h’ same as bellow type.
Step 14-Then go into ‘TableViewController.h’ and give ‘Delegate’ and ‘Datasource’.
-UITableViewDelegate
-UITableViewDataSource
also import classes
#import "FMDB.h"
#import "ViewController.h"
#import "MyCell.h"
#import "FMDatabase.h"
After that give identifiier name into 'Main.storyboard' by clicking on connection where we given push segue and into this 'Attributes Inspector' who name is 'databaseRecords'.
Step 15-Here we have need to add framework ’Libaqlite3.0.dylib’ from Click on our project name FMDB Demo ->Build Phases ->Link to Binary With Libraries. And also we have to need import this framework into ‘ViewController.h’.
#import <sqlite3.h>
Step 16- Here give you all code where we was reach.
——ViewController.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "FMDB.h"
#import "TableViewController.h"
@interface ViewController : UIViewController
{
FMDatabase *db;
}
@property (strong, nonatomic) IBOutlet UITextField *idField;
@property (strong, nonatomic) IBOutlet UITextField *nameField;
@property (strong, nonatomic) IBOutlet UITextField *genderField;
- (IBAction)addButton:(id)sender;
- (IBAction)tblDetail:(id)sender;
@end
——ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize idField,nameField,genderField;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open]) {
return;
}
if (![db tableExists:@"mainuserdetail"])
{
[db executeUpdate:@"CREATE table mainuserdetail(mainUserID text,name text,gender text)"];
[db close];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)addButton:(id)sender {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open])
{
return;
}
NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO mainuserdetail VALUES ('%@','%@','%@')" ,idField.text,nameField.text, genderField.text ];
NSLog(@"%@",insertQuery);
[db executeUpdate:insertQuery];
[db close];
idField.text = @"";
nameField.text = @"";
genderField.text = @"";
}
- (IBAction)tblDetail:(id)sender {
[self performSegueWithIdentifier:@"databaseRecords" sender:nil];
}
@end
——TableViewController.h
#import <UIKit/UIKit.h>
#import "FMDB.h"
#import "ViewController.h"
#import "MyCell.h"
#import "FMDatabase.h"
@interface TableViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *arrData;
NSMutableDictionary *dict;
IBOutlet UITableView *tblView;
}
@end
——TableViewController.m
#import "TableViewController.h"
@interface TableViewController ()
@end
@implementation TableViewController
-(void)viewWillAppear:(BOOL)animated{
arrData = [[NSMutableArray alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
FMDatabase *db = [FMDatabase databaseWithPath:filePath];
[db open];
NSString *sqlSelectQuery = @"SELECT * FROM mainuserdetail";
FMResultSet *Query = [db executeQuery:sqlSelectQuery];
while([Query next]) {
NSString *mainUserid = [NSString stringWithFormat:@"%d",[Query intForColumn:@"mainUserID"]];
NSString *name = [NSString stringWithFormat:@"%@",[Query stringForColumn:@"name"]];
NSString *gender = [NSString stringWithFormat:@"%@",[Query stringForColumn:@"gender"]];
// loading your data into the array, dictionaries.
NSLog(@"mainUserID = %@, name = %@, gender = %@",mainUserid, name, gender);
dict = [[NSMutableDictionary alloc]init];
[dict setObject:mainUserid forKey:@"mainUserID"];
[dict setObject:name forKey:@"name"];
[dict setObject:gender forKey:@"gender"];
[arrData addObject:dict];
}
NSLog(@"arr is : %@",arrData);
[db close];
[tblView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return arrData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.idLabel.text = [arrData [indexPath.row] valueForKey:@"mainUserID"];
cell.nameLabel.text = [arrData [indexPath.row] valueForKey:@"name"];
cell.genderLabel.text = [arrData [indexPath.row] valueForKey:@"gender"];
return cell;
}
@end
Now Check into ‘MyCell.h’
——MyCell.h
#import <UIKit/UIKit.h>
#import "FMDB.h"
#import "ViewController.h"
#import "TableViewController.h"
@interface MyCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *idLabel;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *genderLabel;
@end
Step 17-Now press run the you show bellow type window then add data by put some data into textfield then press ‘ADD’ button. Now whenever you will want to see data then press ‘View Detail’ button.
Step 18-When you will press ‘View Detail’ button then you can see your data is saved into memory.
Here this is only for add data but we have want to change or delete our data that’s for give bellow.
Step 19-Now take one other file and give that class name ‘UpdateViewController’ where subclass of ‘UIViewController’.
Step 20-Now go into ‘Main.storyboard’ and take ViewController from ‘Object Library’ by drag and drop then give class name ‘UpdateViewContoller’ that is given bellow.
Step 21-Now go into ‘UpdateViewController.h’ and import the classes.
#import "FMDB.h"
#import "ViewController.h"
#import "TableViewController.h"
#import "MyCell.h"
#import "FMDatabase.h"
Step 22-After that create bellow type platform into ‘Main.storyboard’ then give ‘Outlet’ and ‘Action’ by drag and drop into ‘UpdateViewController.h’
Step 23-Now give ’Segue’ by right click on ’TableViewController’ then drag and drop on ‘UpdateVIewContoller’ and give ‘push’ same as bellow type.
Step 24-Then give name of identifier when you are click on our connection then into ‘Attributes Inspectore’ and give identifier name ‘return’ or whatever you want.
Step 25-Now import class of ‘UpdateViewController.h’ in all controller i.e. ‘ViewController.h’,’TableViewController.h’ and ‘MyCell.h’.
#import "UpdateViewController.h"
Step 26- Now write take property of database into ‘UpdateViewController.h’ file
{
FMDatabase *db;
}
@property (strong,nonatomic) NSMutableDictionary *updateDict;
Step 27-Now write query into ‘UpdateViewContoller.m’ into the ‘ViewDidLoad’.
- (void)viewDidLoad {
[super viewDidLoad];
idFieldUpdate.text = [updateDict objectForKey:@"mainUserID"];
nameFieldUpdate.text = [updateDict objectForKey:@"name"];
genderFieldUpdate.text = [updateDict objectForKey:@"gender"];
NSLog(@"Update data :%@",updateDict);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
db = [FMDatabase databaseWithPath:filePath];
if (![db open]) {
return;
}
if (![db tableExists:@"mainuserdetail"])
{
[db executeUpdate:@"CREATE table mainuserdetail(mainUserID text,name text,gender text)"];
[db close];
}
Step 28-Now write code into the ‘update’ button.
if (![db open])
{
return;
}
[db open];
NSString *updateQuery = [NSString stringWithFormat:@"UPDATE mainuserdetail SET name='%@',gender='%@' WHERE mainUserID=%@",nameFieldUpdate.text,genderFieldUpdate.text,idFieldUpdate.text];
NSLog(@"update:%@",updateQuery);
[db executeUpdate:updateQuery];
[db close];
here give into picture also
Step 29- Here write code for delete into delete button.
if (![db open])
{
return;
}
[db open];
NSString *deleteQuery = [NSString stringWithFormat:
@"DELETE FROM mainuserdetail WHERE name='%@' and gender='%@' and mainUserID='%@'",nameFieldUpdate.text,genderFieldUpdate.text,idFieldUpdate.text];
[db executeUpdate:deleteQuery];
[db close];
idFieldUpdate.text = nameFieldUpdate.text = genderFieldUpdate.text =@"";
here that is also given into the bellow picture.
Step 30- Now write into TableViewController for ‘didSelsect’ method and segue.
— .h
{
NSMutableArray *arrData;
NSMutableDictionary *dict;
IBOutlet UITableView *tblView;
int indexpath;
}
@property (strong, nonatomic) NSString *update;
—.m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"index path :%ld",(long)indexPath.row);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Section:%ld Row:%ld selected and its data is %@",
(long)indexPath.section,(long)indexPath.row,cell.imageView.image);
indexpath = (int)indexPath.row;
[self performSegueWithIdentifier:@"return" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UpdateViewController *update = segue.destinationViewController;
update.updateDict = arrData[indexpath];
}
Step 31-Here we are given all code of this project.
— —ViewController.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "FMDB.h"
#import "TableViewController.h"
#import "UpdateViewController.h"
@interface ViewController : UIViewController
{
FMDatabase *db;
}
@property (strong, nonatomic) IBOutlet UITextField *idField;
@property (strong, nonatomic) IBOutlet UITextField *nameField;
@property (strong, nonatomic) IBOutlet UITextField *genderField;
- (IBAction)addButton:(id)sender;
- (IBAction)tblDetail:(id)sender;
@end
— —ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize idField,nameField,genderField;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open]) {
return;
}
if (![db tableExists:@"mainuserdetail"])
{
[db executeUpdate:@"CREATE table mainuserdetail(mainUserID text,name text,gender text)"];
[db close];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)addButton:(id)sender {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
NSLog(@"%@",filePath);
db = [FMDatabase databaseWithPath:filePath];
if (![db open])
{
return;
}
NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO mainuserdetail VALUES ('%@','%@','%@')" ,idField.text,nameField.text, genderField.text ];
NSLog(@"%@",insertQuery);
[db executeUpdate:insertQuery];
[db close];
idField.text = @"";
nameField.text = @"";
genderField.text = @"";
}
- (IBAction)tblDetail:(id)sender {
[self performSegueWithIdentifier:@"databaseRecords" sender:nil];
}
@end
— —TableViewController.h
#import <UIKit/UIKit.h>
#import "FMDB.h"
#import "ViewController.h"
#import "MyCell.h"
#import "FMDatabase.h"
#import "UpdateViewController.h"
@interface TableViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *arrData;
NSMutableDictionary *dict;
int indexpath;
IBOutlet UITableView *tblView;
}
@property (strong, nonatomic) NSString *update;
@end
— —TableViewController.m
#import "TableViewController.h"
@interface TableViewController ()
@end
@implementation TableViewController
-(void)viewWillAppear:(BOOL)animated{
arrData = [[NSMutableArray alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
FMDatabase *db = [FMDatabase databaseWithPath:filePath];
[db open];
NSString *sqlSelectQuery = @"SELECT * FROM mainuserdetail";
FMResultSet *Query = [db executeQuery:sqlSelectQuery];
while([Query next]) {
NSString *mainUserid = [NSString stringWithFormat:@"%d",[Query intForColumn:@"mainUserID"]];
NSString *name = [NSString stringWithFormat:@"%@",[Query stringForColumn:@"name"]];
NSString *gender = [NSString stringWithFormat:@"%@",[Query stringForColumn:@"gender"]];
// loading your data into the array, dictionaries.
NSLog(@"mainUserID = %@, name = %@, gender = %@",mainUserid, name, gender);
dict = [[NSMutableDictionary alloc]init];
[dict setObject:mainUserid forKey:@"mainUserID"];
[dict setObject:name forKey:@"name"];
[dict setObject:gender forKey:@"gender"];
[arrData addObject:dict];
}
NSLog(@"arr is : %@",arrData);
[db close];
[tblView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return arrData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.idLabel.text = [arrData [indexPath.row] valueForKey:@"mainUserID"];
cell.nameLabel.text = [arrData [indexPath.row] valueForKey:@"name"];
cell.genderLabel.text = [arrData [indexPath.row] valueForKey:@"gender"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"index path :%ld",(long)indexPath.row);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Section:%ld Row:%ld selected and its data is %@",
(long)indexPath.section,(long)indexPath.row,cell.imageView.image);
indexpath = (int)indexPath.row;
[self performSegueWithIdentifier:@"return" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UpdateViewController *update = segue.destinationViewController;
update.updateDict = arrData[indexpath];
}
@end
— —MyCell.h
#import <UIKit/UIKit.h>
#import "FMDB.h"
#import "ViewController.h"
#import "TableViewController.h"
#import "UpdateViewController.h"
@interface MyCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *idLabel;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *genderLabel;
@end
— —MyCell.m
#import "MyCell.h"
@implementation MyCell
@synthesize idLabel,nameLabel,genderLabel;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
— —UpdateViewController.h
#import <UIKit/UIKit.h>
#import "FMDB.h"
#import "ViewController.h"
#import "TableViewController.h"
#import "MyCell.h"
#import "FMDatabase.h"
@interface UpdateViewController : UIViewController
{
FMDatabase *db;
}
@property (strong,nonatomic) NSMutableDictionary *updateDict;
@property (strong, nonatomic) IBOutlet UITextField *idFieldUpdate;
@property (strong, nonatomic) IBOutlet UITextField *nameFieldUpdate;
@property (strong, nonatomic) IBOutlet UITextField *genderFieldUpdate;
- (IBAction)update:(id)sender;
- (IBAction)delete:(id)sender;
@end
— —UpdateViewController.m
#import "UpdateViewController.h"
@interface UpdateViewController ()
@end
@implementation UpdateViewController
@synthesize idFieldUpdate,nameFieldUpdate,genderFieldUpdate,updateDict;
- (void)viewDidLoad {
[super viewDidLoad];
idFieldUpdate.text = [updateDict objectForKey:@"mainUserID"];
nameFieldUpdate.text = [updateDict objectForKey:@"name"];
genderFieldUpdate.text = [updateDict objectForKey:@"gender"];
NSLog(@"Update data :%@",updateDict);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDirectory,@"medistory.db"];
db = [FMDatabase databaseWithPath:filePath];
if (![db open]) {
return;
}
if (![db tableExists:@"mainuserdetail"])
{
[db executeUpdate:@"CREATE table mainuserdetail(mainUserID text,name text,gender text)"];
[db close];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)update:(id)sender {
if (![db open])
{
return;
}
[db open];
NSString *updateQuery = [NSString stringWithFormat:@"UPDATE mainuserdetail SET name='%@',gender='%@' WHERE mainUserID=%@",nameFieldUpdate.text,genderFieldUpdate.text,idFieldUpdate.text];
NSLog(@"update:%@",updateQuery);
[db executeUpdate:updateQuery];
[db close];
}
- (IBAction)delete:(id)sender {
if (![db open])
{
return;
}
[db open];
NSString *deleteQuery = [NSString stringWithFormat:
@"DELETE FROM mainuserdetail WHERE name='%@' and gender='%@' and mainUserID='%@'",nameFieldUpdate.text,genderFieldUpdate.text,idFieldUpdate.text];
[db executeUpdate:deleteQuery];
[db close];
idFieldUpdate.text = nameFieldUpdate.text = genderFieldUpdate.text =@"";
}
@end
Step 32-Now run your project and add data one by one like given bellow.
Step 33- When you press ‘View Detail’ button then you can see bellow type window.
Step 34-After that whenever you want to change or delete you data then select that by single click and you can see bellow type window here you can give event by pressing buttons.
Step 35-If you want to update data then follow bellow
Step 36-Otherwise you want to delete them so press delete button and you can see bellow type table.
Comments