3

在这里,我想使用两个数据库执行查询并将数据从 database1 的表复制到另一个 database2。在这里我可以打开一个数据库,但在打开其他数据库时遇到问题。在此先感谢大家。

CurrentStatus *status = [CurrentStatus sharedCurrentStatus];
    sqlite3 *database;
    sqlite3 *database1;
    sqlite3_stmt *statement;
    sqlite3_stmt *statement1;
    NSString *dbPath = [status.applicationDocumentDirectory stringByAppendingPathComponent:@"database.sqlite"];
    NSString *dbPath1 = [status.applicationDocumentDirectory stringByAppendingPathComponent:@"database1.sqlite"];

    if ((sqlite3_open_v2([dbPath UTF8String], &database, SQLITE_OPEN_READWRITE , NULL) == SQLITE_OK) && (sqlite3_open_v2([dbPath1 UTF8String], &database1, SQLITE_OPEN_READWRITE , NULL) == SQLITE_OK)) {

        NSString *sqlStr = [[NSString alloc] initWithFormat:@"select * from Login" ];
         NSString *sql = [[NSString alloc] initWithString:sqlStr];

                if ((sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)) {
                    NSLog(@"DB prepare_v2 Opening successfully");
                    if (sqlite3_step(statement) == SQLITE_ROW) {

                    }
                    else
                    {

                    }
                    sqlite3_finalize(statement);
        NSLog(@"DB Opening successfully");

               sqlite3_close(database);
    }else
    {
        NSLog(@"else DB Opening successfully");
    }
        sqlite3_close(database);
    }
4

3 回答 3

2

尝试类似的事情来完成你的任务..

首先,您正在打开“DB1”数据库,然后执行以下语句:

ATTACH DATABASE "2ndDB.db" AS 2ndDB;

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

CREATE TABLE newTableInDB1 AS SELECT * FROM 2ndDB.oldTableInMyOtherDB;

这会将数据“复制”到您的新数据库中

于 2013-10-25T05:36:31.857 回答
1

从 database1 复制您想要的数据,将每一行添加到 NSMutableDictionary 中,然后将其添加到 NSMutableArray。关闭并重置您的语句,然后打开数据库2从 NSMutableArray 复制数据,该数组充当您的数据库..

我希望它对你有用..

于 2013-10-25T05:28:20.803 回答
1

您需要您需要附加数据库,然后将表从一个数据库复制到另一个数据库。你需要做这样的事情:

NSString *attachSQL = [NSString stringWithFormat: @"ATTACH DATABASE \'%s\' AS %@", sourceDBPath,dbAlias];

if (sqlite3_exec(db, [attachSQL UTF8String], NULL, NULL, &errorMessage) != SQLITE_OK)
   {
        NSString *errorStr = [NSString stringWithFormat:@"The database could not be attached: %@",[NSString stringWithCString:errorMessage encoding:NSUTF8StringEncoding]];  
        return errorStr;
   }

之后,您需要复制 table ,例如:

NSString *queryString=[NSString stringWithFormat:@"CREATE TABLE %@ AS SELECT * FROM %@.%@;",newTableName,dbAlias,origTableName];

你完成了,你有了新的数据库副本。

于 2013-10-25T05:48:03.070 回答