8

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


}

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

4

2 回答 2

22

在 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

于 2012-05-08T20:46:40.997 回答
0

经过数小时的 SO 斗争,并在上述帖子的帮助下,我终于能够为此创建 Objective-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);
}
于 2015-09-16T12:03:16.557 回答