FMDB implimentation in IOS Applications

Introduction

FMDB stands for Flying Meat Database. FMDB is a framework where they provide easy way to use SQLite Database in IOS applications.

You can  find all information about this framework at https://github.com/ccgus/fmdb.

This article  will give you a brief introduction about how to  use  FMDB to create a database, create a table, insert, fetch, and delete data.

Initial Setup

Step 1 : First download the FMDB framework .
Step 2 : Extract the framework and copy all the files from src folder in application.
Step 3 : Click your project in the left column of XCode.
Step 4 : Click the main target in the middle column.
Step 5 : Click the “Build Phases” tab.
Step 6 : Expand the arrow next to “Link Binary With Libraries”.
Step 7 : Click the “+” button.

1

Step 8 : Search for libsqlite3.0.dylib and click on Add button.

2

When you are all done, it should look like this

3

Now, that we have the library and FMDB Framework.

Create SQLite Database file 

Create the SQLite Database file in your application’s using following steps.

Right Click on  your project in the left column of XCode. Select “New File” ,Select the “Other” in iOS section ,select “Empty” documentation and click on next button.

4

Provide the database-name with .sqlite extension (Ex. database-name.sqlite). Check mark all “Targets” and click on create button.

5

Copy your existing database into app’s document in didFinishLaunchingWithOptions: and maintain the database path through out the application.

In your AppDelegate add the following code.

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

// Application Start
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Function called to create a copy of the database if needed.
[self createCopyOfDatabaseIfNeeded];
return YES;
}
#pragma mark - Defined Functions
// Function to Create a writable copy of the bundled default database in the application Documents directory.

- (void)createCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// Database filename can have extension db/sqlite.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"database-name.sqlite"];
success = [fileManager fileExistsAtPath:appDBPath];
if (success){
return;
}
 // The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database-name.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}

Database Operations

We perform all operations (create table,insert,select,update,delete) on database. First we need to import FMDatabase.h in our class and used all this methods for database operations.

1. Create Tables 

#import "FMDatabase.h"

- (void)createTable {
    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    [database executeUpdate:@"create table if not exists college(name varchar primary key, ID int)"];
    [database close]; 
}

2. Insert Data In Tables

#import "FMDatabase.h"

- (void)insertDataInDB {

    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];    
    NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO college VALUES ('%@', %d)", @"PCE College", 1];
    [database executeUpdate:insertQuery];   
    [database close];
}

3. Fetch Data From Tables

#import "FMDatabase.h"
- (void)getAllDataFromDB {
    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    NSString *sqlSelectQuery = @"SELECT * FROM college";

    // Query result 
    FMResultSet *resultsWithCollegeName = [database executeQuery:sqlSelectQuery];
    while([resultsWithCollegeName next]) {
        NSString *collgeID = [NSString stringWithFormat:@"%d",[resultsWithCollegeName intForColumn:@"ID"]];
        NSString *collegeName = [NSString stringWithFormat:@"%@",[resultsWithCollegeName stringForColumn:@"name"]];

        // save your fetch data into the array, dictionaries.
        NSLog(@"ID = %d, Name = %@",collegeID, collegeName);
    }
    [database close];   
}

4.Update Data In Tables

- (void)updateDataInDB {

    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];    
    NSString *updateQuery = [NSString stringWithFormat:@"UPDATE college SET ID = '%@' WHERE name = '%@'", @"2", @"PCE College" ];
    [database executeUpdate:updateQuery];
    [database close];

}

5. Delete Data From Tables

#import "FMDatabase.h"

- (void)deleteDataInDB {

    // Getting the database path.
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];

    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    NSString *deleteQuery = @"DELETE FROM college WHERE ID = 2";
    [database executeUpdate:deleteQuery];   
    [database close];
}

 

 

The following two tabs change content below.

Naveen Kumar Dungarwal

Latest posts by Naveen Kumar Dungarwal (see all)

3 Comments

  1. Let me know any new updates

  2. Good Tutorial Thanks so match

  3. good tutorials

Submit a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current month ye@r day *