打开两个sqlite数据库并在iphone中执行查询

时间:2013-10-25 05:17:23

标签: ios iphone sqlite

这里我想使用两个数据库执行查询,并将数据从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);
    }

3 个答案:

答案 0 :(得分:2)

尝试类似的东西来实现你的任务..

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

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

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

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

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

答案 1 :(得分:1)

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

我希望它对你有用..

答案 2 :(得分: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;
   }

之后你需要复制表格,如:

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

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