iossqlitefmdb

How to use two sqlite database files in single iOS project with simultaneously fetch data from both Database


My requirement is to add two SQLite database files in my project. I know that is possible. But how can I access two database files simultaneously?

One more thing currently I am using FMDB to manipulate database operation.

Note : Both of my DB file sizes are near about 1GB each. so also want to know that if I use 2 DB file so is there any memory issue will occur in my application ?

Thanks.


Solution

  • Generally, there is rare requirement of 2 Database files in a single project specially in iOS where we have used only one DB.

    But as per your requirement, we can use multiple Database files in a single project with multiple Database instances.

    To Create 2 instance use below code for SQLite Native:

    //Create Object of DataBase
    static sqlite3 *databaseOne = nil;
    static sqlite3 *databaseTwo = nil;
    
    //Open Both Databases while we needed in our project 
    
    //Open First Database
    sqlite3_open([path UTF8String], &databaseOne);
    
    //Opne Second Database
    sqlite3_open([path UTF8String], &databaseTwo);
    
    //prepare for statement execution
    
    sqlite3_prepare_v2(databaseOne, [sql UTF8String], -1, &stmt, NULL)
    
    sqlite3_prepare_v2(databaseTwo, [sql UTF8String], -1, &stmt, NULL)
    

    But make sure you will not mix these 2 objects while executing.

    Note: Close both connections while your DB task is done.

    To Create 2 instance with FMDB use below code:

    //First DB
    FMDatabase *dbOne = [FMDatabase databaseWithPath:<your first DB file Path>];
    [dbOne open];
    //Do Your DB task
    [dbOne close];
    
    //Second DB 
    FMDatabase *dbTwo = [FMDatabase databaseWithPath:<your second DB file Path>];
    [dbTwo open];
    //Do Your Second DB task
    [dbTwo close];
    

    Hope this will help you.