使用Xcode

时间:2018-03-26 00:18:49

标签: ios swift sqlite fmdb

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

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

我使用FMDB库来访问SQLite DB。

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

  1. openDB
  2. COPYDB
  3. 的executeQuery
  4. 因为虽然打包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
    }
    

    以下是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
    }
    

    及以下是执行查询的代码

    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)
        }
    }
    

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

      

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

2 个答案:

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

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

答案 1 :(得分:1)

  Firstly Create FileManager Object. Get Path and check file is exist or not then copy items from db.
     func callForCopyDBAllObejct() -> Bool {
     let fileM = FileManager.default
     var dbPath = nil

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

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

}