Insert data into database(SQLITE) in Iphone


In this tutorial we will see how can we insert and access the value from the Database and these values fetch into table view. In this application we use SQLITE Manager as a backend. This is the navigation based application. Here are some steps for it…



1. Open the xcode & choose "File->New Project".

2. Select "Application" from left menu and then "View-based Application".

3.Name your project as "InsertData" and save the project.

4.Here we need to import the sqlite framework from the library

  right click on framework and add the libsqlite3.0 framework.

5.Now add the database file into resource folder.(Right click onto the resource folder and the database file which we have created in sqlite manager).

 

6.Now just select "RootViewController.h" file from left menu .

 

 

 

#import <UIKit/UIKit.h>

#import "InsertDataAppDelegate.h"

#import "SecondViewController.h"

#import "Item.h"

@class Item;

@interface RootViewController : UITableViewController {

InsertDataAppDelegate *appdelegate;

SecondViewController *viewController;

UINavigationController *addNavigationController;


}


@end

 

 

7. Now select "RootViewController.m" file from menu for implementation.

 

#import "RootViewController.h"

#import "InsertDataAppDelegate.h"

#import "SecondViewController.h"

#import "Item.h"


@implementation RootViewController



#pragma mark -

#pragma mark View lifecycle



- (void)viewDidLoad {

    [super viewDidLoad];


    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.

    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.navigationItem.title=@"item";

self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc

initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 

target:self action:@selector(add_Clicked:)];

appdelegate = (InsertDataAppDelegate *)[[UIApplication sharedApplication] delegate];

}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

[self.tableView reloadData];

}



- (void) add_Clicked:(id)sender {

if(viewController == nil)

viewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];

if(addNavigationController == nil)

addNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController];

[self.navigationController presentModalViewController:addNavigationController animated:YES];

}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}



// Customize the number of rows in the table view.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [appdelegate.array count];

}



// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    

    static NSString *CellIdentifier = @"Cell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    }

    Item *Obj = [appdelegate.array objectAtIndex:indexPath.row];

//Set the coffename.

cell.text = Obj.name;

cell.detailTextLabel.text=Obj.address;

// Configure the cell.


    return cell;

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the row from the data source.

Item *Obj = [appdelegate.array objectAtIndex:indexPath.row];

[appdelegate removeitem:Obj];


        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }   

    

}



- (void)dealloc {

    [super dealloc];

}



@end



8.Now we have to create  and read the database in sqliteAppDelegate.m.


#import "InsertDataAppDelegate.h"

#import "RootViewController.h"

#import <sqlite3.h>

#import "Item.h"





@implementation InsertDataAppDelegate


@synthesize window;

@synthesize navigationController,array,databaseName,databasePath;



#pragma mark -

#pragma mark Application lifecycle


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    

    // Override point for customization after application launch.

    

[self copyDatabaseIfNeeded];

//Initialize the coffee array.

NSMutableArray *tempArray = [[NSMutableArray alloc] init];

self.array = tempArray;

[tempArray release];

//Once the db is copied, get the initial data to display on the screen.

[Item getInitialDataToDisplay:[self getDBPath]];

    // Add the navigation controller's view to the window and display.

    [window addSubview:navigationController.view];

    [window makeKeyAndVisible];


    return YES;

}

- (void)applicationWillTerminate:(UIApplication *)application {

// Save data if appropriate

[Item finalizeStatements];

}


- (void) copyDatabaseIfNeeded {

//Using NSFileManager we can perform many file system operations.

NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *error;

NSString *dbPath = [self getDBPath];

BOOL success = [fileManager fileExistsAtPath:dbPath]; 

if(!success) {

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Mydatabase.sqlite"];

success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

if (!success) 

NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

}

}


- (NSString *) getDBPath {

//Search for standard documents using NSSearchPathForDirectoriesInDomains

//First Param = Searching the documents directory

//Second Param = Searching the Users directory and not the System

//Expand any tildes and identify home directories.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);

NSString *documentsDir = [paths objectAtIndex:0];

return [documentsDir stringByAppendingPathComponent:@"Mydatabase.sqlite"];

}



-(void)Additem:(Item*)itemobj {

//Add it to the database.

[itemobj addItem];

//Add it to the coffee array.

[array addObject:itemobj];

}


-(void)removeitem:(Item *)itmObj {

//Delete it from the database.

[itmObj deleteItem ];

//Remove it from the array.

[array removeObject:itmObj];

}


- (void)dealloc {

[navigationController release];

[window release];

[super dealloc];

}



@end


 

 

9. Then Quit and Save the Interface Builder.


10. Now you are ready for  click on "Build & Go" button. 


Now you can see the output in iphone simulator .

 



(11) Responses to this post

Cordelia May 05 2011 at 19:32:08

That saves me. Thanks for being so sneslbie!

mfvfzk May 05 2011 at 22:27:33

uhNlXX dycbqtgltccb

backlinks Nov 27 2011 at 21:46:26

greetings iphonetut.com blogger found your blog via Google but it was hard to find and I see you could have more visitors because there are not so many comments yet. I have discovered site which offer to dramatically increase traffic to your website http:

unsupewhise Dec 11 2011 at 14:15:38

Earn up to $3500/month just by taking simple surveys online! I tried one of those online survey sites about 4 months ago that say all you have to do is spend a couple of minutes filling out some surveys and you will be making hundreds a

Houggittign Jan 03 2012 at 01:45:27

Yes, that’s right. We’ll pay you $25 when you sign up with us today! We have an instant $25 market research survey you can take as soon as you join. http://get-money-for-your-opinion.info Imagine companies paying you just to

J Jan 05 2012 at 20:45:33

Thanks for the code. But there is a problem here. The data is only inserted into memory database...after resetting the application, none of updating are shown. Much appreciate if you check out the code and repost a solution. Thanks!

J Jan 05 2012 at 21:13:57

Thanks for the code. But there is a problem here. The data is only inserted into memory database...after resetting the application, none of updating are shown. Much appreciate if you check out the code and repost a solution. Thanks!

ravinder Apr 16 2012 at 23:46:46

this is really a big one for me thank you very very much for your job...

ricky Apr 17 2012 at 00:26:13

can anyone suggest me how to get started with Xcode from its basics in a clear and efficient way (e.g. book/ebook/articles/site/whatever) plz reply waiting... thanks in advance...

ricky Apr 17 2012 at 00:48:48

can anyone suggest me how to get started with Xcode from its basics in a clear and efficient way (e.g. book/ebook/articles/site/whatever) plz reply waiting... thanks in advance...

obaid May 16 2012 at 02:09:00

Hello, i got this tutorial but dude you are only showing the data from the database file but you are not inserting it. You are also knows it better.


Leave your comment here






User Login




New User Forgot password

Newsletter Subscribe

Advertisement

 
 
 
quick contact