4

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

2 Answers2

8

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

Tommy
  • 99,986
  • 12
  • 185
  • 204
1

No, you can't. But there should not be any drawbacks doing the JOIN with Objective-C-code instead of using SQ (except that you might be more comfortable doing a JOIN in SQL rather than Objective-C).

Related: How to Merge Multiple Database files in SQLite?

Community
  • 1
  • 1
Simeon
  • 5,519
  • 3
  • 29
  • 51