Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C SQLite join tables from multiple database

I am working on an IPAD project. The project has 2 sqlite database. the first one say customer.sqlite and the second one called address.sqlite. Customer.sqlite comes along with the app and the address.sqlite is downloaded from the server every time the app is started. Everything works fine. The question i have here, can i do a join on 2 tables that are in 2 different database using objective-c.

I can open a connection to a single database using sqlite3_open(filename, sqliteconnection), how do i attach another database to the same connection? Is that possible??

Thanks

Suresh Kumar Narayanasamy

like image 718
Suresh Kumar Narayanasamy Avatar asked Jan 19 '23 05:01

Suresh Kumar Narayanasamy


1 Answers

Ok found out the answer. Below is the sample code

sqlite3 *_myLocalConnection;

if (sqlite3_open([["Your First DB file path"] UTF8String], &_myLocalConnection) == SQLITE_OK)
{
   NSString *strSQLAttach = [NSString stringWithFormat:@"ATTACH DATABASE \'%s\' AS SECOND", [["Your second db file path"] UTF8String] ];
   char *errorMessage;

   if (sqlite3_exec(_myLocalConnection, [strSQLAttach UTF8String], NULL, NULL, &errorMessage) == SQLITE_OK)
   {
      sqlite3_stmt *myStatment;

      NSString *strSQL = @"select * from SECOND.ADDRESS myAddress inner join main.CUSTTOMER myCustomer on myAddress.CustomerID = myCustomer.customerID ";      

      if (sqlite3_prepare_v2(_myLocalConnection, [strSQL UTF8String], -1, &myStatment, nil) == SQLITE_OK)
        //do your loop logic
      else
         NSLog(@"Error while attaching '%s'", sqlite3_errmsg(_myLocalConnection));

     }
}    

Thanks

Suresh Kumar Narayanasamy

like image 196
Suresh Kumar Narayanasamy Avatar answered Jan 31 '23 04:01

Suresh Kumar Narayanasamy