使用Xcode将预加载的sqlite db添加到iOS App后找不到表

Roo*_*kie 7 sqlite fmdb ios swift

我有一个预加载的SQLite数据库,名为"myDB.dms".我想打包数据库并从应用程序中访问内容.

首先,我在我的Xcode ProjectNavigator窗口中拖放数据库文件,然后在提示中点击"如果需要复制文件".

我使用FMDB库来访问SQLite DB.

我创建了一个新的Database接口类并添加了3种不同的方法:

  1. openDB
  2. COPYDB
  3. 的executeQuery

因为虽然打包DB文件将在Bundle资源文件夹中,但我必须将资源文件夹中的文件复制到目录文件夹,如下所示:

func copyDB() -> Bool {
    let fileManager = FileManager.default
    let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    var returnStatus: Bool = false

    guard documentsUrl.count != 0 else {
        print("Could not find documents url")
        return false
    }

    let finalDatabaseURL = documentsUrl.first!.appendingPathComponent(dbFileName)

    if !((try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
        print("DB does not exist in documents folder")

        let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(dbFileName)

        do {
            try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
        } catch let error as NSError {
            print ("Couldnt copy file to final location! Error:\(error.description)")
            returnStatus = false
        }
    } else {
        print ("Database file found at path: \(finalDatabaseURL.path)")
        returnStatus = true
    }

    return returnStatus
}
Run Code Online (Sandbox Code Playgroud)

下面是OpenDatabase的代码

func openDB() -> Bool {
    let fileManager = FileManager.default
    let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    let dbPath = documentsUrl.first!.appendingPathComponent(dbFileName)
    let database = FMDatabase(url: dbPath)

    var returnStatus: Bool = false

    if (self.copyDB() == false) {
        returnStatus = false
    } else {
        if (!database.open(withFlags: 1)) {
            print("Could not open database at \(dbPath.absoluteString)")
            returnStatus = false
        } else {
            self.database = database
            returnStatus = true
        }
    }

    return returnStatus
}
Run Code Online (Sandbox Code Playgroud)

以下是执行查询的代码

func executeQuery(queryString:String) {
    print(queryString)
    do {
        if (database.open()){
            let results:FMResultSet = try database.executeQuery(queryString, values: nil)

            if results.next() == true {
                print(results)
            }
        }
    } catch let error as NSError {
        print(error.description)
    }
}
Run Code Online (Sandbox Code Playgroud)

copyDB()和openDB()工作正常,但后来我尝试执行Query(),我得到以下错误:

错误域= FMDatabase代码= 1"没有这样的表:tableName"UserInfo = {NSLocalizedDescription = no such table:tableName}

Roo*_*kie 2

下面是有效的代码:

    func copyDataBase() -> Bool {
    let fileManager = FileManager.default
    var dbPath = ""

    do {
        dbPath = try fileManager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent(dbFileName).path
    } catch {
        print(error.localizedDescription)
        return false
    }

    if !fileManager.fileExists(atPath: dbPath) {
        let dbResourcePath = Bundle.main.path(forResource: "dbName", ofType: "sqlite")
        do {
            try fileManager.copyItem(atPath: dbResourcePath!, toPath: dbPath)
        } catch {
            print(error.localizedDescription)
            return false
        }
    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

我希望这能帮助有需要的人