将一个数据库中的表复制到另一个数据库

我想从aDB复制表到另一个bDB。

所以我做了一个方法。 我认为打开2数据库和使用插入查询将工作,但我不知道详细的方式。

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

这样对吗? 以及如何做更多? //来源复制区域。

在sqlite3中,可以结合ATTACH [1]和CREATE TABLE .. AS [2]命令:

首先,打开“bDB”数据库,然后执行以下语句:

 ATTACH DATABASE "myother.db" AS aDB; 

之后,您可以使用CREATE TABLE语法:

 CREATE TABLE newTableInDB1 AS SELECT * FROM aDB.oldTableInMyOtherDB; 

这会将数据“复制”到新的数据库中。 如果你想合并数据,还有一个INSERT [3]语句,但是你需要引用你的字段:

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

参考文献:

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

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

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

经过几个小时的斗争,并在上述post的帮助下,最后我能够为此创buildObjective-C代码。

 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); }