2012-05-06 11 views
5

Quiero copiar la tabla de aDB a otro bDB.Copiando la tabla en un db a otro db

Así que hice un método. Creo que la base de datos abierta 2 y el uso de la consulta de inserción funcionarán, pero no sé la forma detallada.

-(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? 


} 

¿Es correcto? y cómo hacer más? // fuente para copiar el área.

Respuesta

21

en sqlite3, puede combinar la ATTACH [1] y CREATE TABLE AS .. [2] comandos:

primera, que está abriendo la base de datos "BDB", y luego ejecute la siguiente instrucción:

ATTACH DATABASE "myother.db" AS aDB; 

Después de eso, puede utilizar la sintaxis CREATE TABLE:

CREATE TABLE newTableInDB1 AS SELECT * FROM aDB.oldTableInMyOtherDB; 

esto va a "copiar" los datos a través de su nueva base de datos. Si desea combinar los datos, también hay un INSERT [3] Declaración, pero con lo que usted necesita para hacer referencia a los campos de la siguiente manera:

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

Referencias:

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

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

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

+1

+1 para recordarme creación de la tabla rápida y copiar con "CREATE newTableInDB1 TABLA AS SELECT * FROM aDB.oldTableInMyOtherDB;" –

+0

bien explicado. sería genial si puedes escribir en el código concreto de ios objc. – OMGPOP

+0

Los comandos son de SQL puro, los ejecuta con una llamada a sqlite3_exec(). – Zuppa

0

Después de horas de str uggle on SO, y con la ayuda de la publicación anterior, finalmente pude crear código Objective-C para hacer esto.

NSString* dbPath1; 
NSString* dbPath2; 

dbPath1 = [self getDB1Path]; //This db have the desired table to be copied 
dbPath2 = [self getDB2Path]; //This needs to have the desired table 

//open database which contains the desired "table" 
if (sqlite3_open(dbPath1.UTF8String, &databasePhase2) == SQLITE_OK) 
{ 
    NSString *attachSQL = [NSString stringWithFormat: @"ATTACH DATABASE \"%@\" AS phase2_db",dbPath2]; 

    const char *attachSQLChar = [attachSQL UTF8String]; 
    char* errInfo; 
    int result = sqlite3_exec(databasePhase2, attachSQLChar, nil, nil, &errInfo); 

    if (SQLITE_OK == result) 
    { 
     NSLog(@"new db attached"); 
     NSString *attachSQL = [NSString stringWithFormat: @"CREATE TABLE newTableInDB1 AS SELECT * FROM phase2_db.qmAyahInfo"]; 

     const char *createSQLChar = [attachSQL UTF8String]; 
     int result2 = sqlite3_exec(databasePhase2, createSQLChar, nil, nil, &errInfo); 
     if (SQLITE_OK == result2) 
     { 
      NSLog(@"New table created in attached db"); 
     } 
    } 
    sqlite3_close(databasePhase2); 
} 
+0

No olvide separar la base de datos con DETACH DATABASE phase2_db, en caso de que no solo la cierre. – Zuppa

Cuestiones relacionadas