【问题标题】:Reverse engineer a SQLite3 db into coredata将 SQLite3 数据库逆向工程到 coredata
【发布时间】:2011-10-13 23:28:04
【问题描述】:

最初的问题是“我有一个 sqlite 3 db(字典),我想在新应用程序中使用它。基于 db 结构创建核心数据关系模型是否有捷径?”

这就是我解决问题的方法——在网上得到了很多帮助。

我简化了数据库,这使得编写核心数据模型变得非常容易。

我使用来自 great site 的 Python 脚本来管理转换。

脚本如下:

import sqlite3;

inConn = sqlite3.connect('dictold.sqlite')
outConn = sqlite3.connect('dictnew.sqlite')

inCursor = inConn.cursor()
outCursor = outConn.cursor()

maxId = 0
inCursor.execute("select * from lexicon")
for row in inCursor:

    if row[0] > maxId:
        maxId = row[0]

    # Create ZLEXICONENTITY entry
    vals = []
    vals.append(row[3]) # Z_PK
    vals.append(1) # Z_OPT
    vals.append(2) # Z_ENT  
    vals.append(row[0]) # ZIND
    vals.append(row[1]) # ZENGLISH
    vals.append(row[2]) # ZGREEK
    outConn.execute("insert into ZLEXICONENTITY values(?, ?, ?, ?, ?, ?)", vals)


outConn.execute("update Z_PRIMARYKEY set Z_MAX=?", [maxId])

outConn.commit()

一旦我建立了数据库,我在将它连接到 Core Data 模型时遇到了问题。我收到一条消息“模型与数据库不匹配”。

解决方案是让 Core Data 从模型中创建空数据库,然后让 Core Data 自己导入数据。

我首先将我的 sqlite 数据库(使用 Python 创建)导出到调用文件 db.sql 的 sql 中(想象力丰富!)。我只导出了数据表和主键表,没有导出元数据表。您也可以在命令行中执行此操作。我使用了一个名为 SQLiteManager 的应用程序。

Core Data 中的所有代码都是库存的东西,除了处理持久存储控制器。

该代码如下:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }


    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"db.sql"];

    // set up the backing store
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // If the expected store doesn't exist, copy the default store.
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"dict" ofType:@"sqlite"];
        if (defaultStorePath) {
            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
    }

    NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    NSError *error = nil;
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return persistentStoreCoordinator_;
}

可能很多人都知道这一切,但我不得不坚持了几天。也可能有更简单的方法来做到这一点。但也许它会帮助其他人..

【问题讨论】:

    标签: xcode cocoa-touch cocoa core-data sqlite


    【解决方案1】:

    没有。

    Core Data 无法从现有架构推断您的模型,您必须创建模型,然后自行迁移存储。

    【讨论】:

    • 最后,我发现使用 sqlite db 并将其添加到项目中更容易。
    • 您在迁移数据和填充核心数据存储时遇到问题吗?还是您选择不使用 Core Data 而是直接使用 SQLite?
    猜你喜欢
    • 1970-01-01
    • 2011-07-24
    • 2017-05-05
    • 2023-03-24
    • 2011-12-21
    • 2016-01-20
    • 2017-12-31
    • 1970-01-01
    • 2010-10-12
    相关资源
    最近更新 更多