将一个db中的表复制到另一个db

Seo*_*iJi 8 database sqlite copy ios

我想将表从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?


}
Run Code Online (Sandbox Code Playgroud)

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

Zup*_*ppa 21

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

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

ATTACH DATABASE "myother.db" AS aDB;
Run Code Online (Sandbox Code Playgroud)

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

CREATE TABLE newTableInDB1 AS SELECT * FROM aDB.oldTableInMyOtherDB;
Run Code Online (Sandbox Code Playgroud)

这会将数据"复制"到新数据库中.如果要合并的数据,也有一个INSERT [3]的语句,但你需要引用你的领域是这样的:

INSERT INTO newtable (field1,field2) 
  SELECT otherfield1,otherfield2 FROM aDB.oldTableInMyOtherDB;
Run Code Online (Sandbox Code Playgroud)

参考文献:

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

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

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