Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying table in one db to another db

I want to copy table from aDB to another bDB.

So I made a method. I think open 2 database and Using insert query will work but I don't know detail way.

-(void)copyDatabaseTableSoruceFileName:(NSString *)source CopyFileName:(NSString *)copy
{
sqlite3 *sourceDatabase=NULL;
sqlite3 *copyDatabase=NULL;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDir = [paths objectAtIndex:0];

//source
    [self copyFileIfNeed:source path:documentDir];

NSString *SourceDBPath = [documentDir stringByAppendingPathComponent:source];
if( sqlite3_open([SourceDBPath UTF8String],&sourceDatabase)!= SQLITE_OK )
{
    NSLog(@"DB File Open Error :%@", SourceDBPath);
   sourceDatabase = NULL;
}
//copy    
[self copyFileIfNeed:copy path:documentDir];

NSString *CopyDBPath = [documentDir stringByAppendingPathComponent:copy];
if( sqlite3_open([CopyDBPath UTF8String],&copyDatabase)!= SQLITE_OK )
{
    NSLog(@"DB File Open Error :%@", CopyDBPath);
    copyDatabase = NULL;
}

//source to copy


 // How in this area?


}

Is it right? and how to make more ? //source to copy area.

like image 546
SeoTaiJi Avatar asked May 06 '12 13:05

SeoTaiJi


1 Answers

in sqlite3, you can combine the ATTACH[1] and CREATE TABLE .. AS[2] commands:

first, you are opening the "bDB" database, and then execute the following statement:

ATTACH DATABASE "myother.db" AS aDB;

After that, you can use the CREATE TABLE syntax:

CREATE TABLE newTableInDB1 AS SELECT * FROM aDB.oldTableInMyOtherDB;

This will "copy" the data over to your new database. If you want to merge the data, there is also an INSERT[3] statement, but with that you will need to reference your fields like this:

INSERT INTO newtable (field1,field2) 
  SELECT otherfield1,otherfield2 FROM aDB.oldTableInMyOtherDB;

References:

[1] http://www.sqlite.org/lang_attach.html

[2] http://www.sqlite.org/lang_createtable.html

[3] http://www.sqlite.org/lang_insert.html

like image 184
Zuppa Avatar answered Sep 28 '22 03:09

Zuppa