如何在Swift 3中使用现有的SQLite?(FMDB)

fnvucqvd  于 11个月前  发布在  Swift
关注(0)|答案(3)|浏览(122)

我想连接(Salary.db)到我的iOS(Swift)项目并从数据库获取数据?
第一步,如何在Swift 3中连接现有数据库?

let fileURL = try! FileManager.default
            .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent("Salary.db")

guard let database = FMDatabase(path: fileURL.path) else {
    print("unable to create database")
    return
}

guard database.open() else {
    print("Unable to open database")
    return
}

字符串

kcrjzv8t

kcrjzv8t1#

FMDB是一个很棒的Java-C库,它还没有为Swift更新,有时在Swift中感觉很尴尬。
您可以考虑使用像GRDB.swift这样的库,它是用Swift编写的,健壮的,fast,并赠款您与FMDB相同的功能:

import GRDB

// GRDB's DatabaseQueue is similar to FMDB's FMDatabaseQueue
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")

try dbQueue.inDatabase { db in
    // Same as FMDB's -[FMDatabase executeUpdate:withArgumentsInArray:]
    try db.execute(
        "INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " +
        "VALUES (?, ?, ?, ?)",
        arguments: ["Paris", true, 48.85341, 2.3488])

    // Same as FMDB's -[FMDatabase executeQuery:] and FMResultSet
    let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
    while let row = try rows.next() {
        let title: String = row.value(named: "title")
        let isFavorite: Bool = row.value(named: "favorite")
        let coordinate = CLLocationCoordinate2DMake(
            row.value(named: "latitude"),
            row.value(named: "longitude"))
    }
}

字符串
GRDB还允许您在不想写SQL时避免写SQL。有关详细信息,请参阅README.md

yk9xbfzb

yk9xbfzb2#

这里是Swift中SQLite的最佳教程
http://www.appcoda.com/fmdb-sqlite-database/
https://www.raywenderlich.com/123579/sqlite-tutorial-swift
在Github上获取完整的项目:click here
下面是我的代码:
ModelManager.swift

import UIKit
import FMDB
let sharedInstance = ModelManager()
class ModelManager: NSObject {

    var database: FMDatabase? = nil
    var dbPath:String? = nil
    class func getInstance() -> ModelManager
    {
        if(sharedInstance.database == nil)
        {
            let documentsPath1 = NSURL(fileURLWithPath:    NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
            let logsPath = documentsPath1.appendingPathComponent("datadb")

            let dbpath = logsPath?.appendingPathComponent("test.db")
            sharedInstance.database = FMDatabase(path:dbpath?.path)
        }
        return sharedInstance
    }

    func getUserProfile() -> Dictionary<String, String> {

        sharedInstance.database!.open()
        let strQuery = "select * from tbl_UserProfile  limit 1"
        let resultSet: FMResultSet! = sharedInstance.database!.executeQuery(strQuery, withArgumentsIn: nil)
        var dict:Dictionary<String, String> = [:]
        if (resultSet != nil) {
            while resultSet.next() {
                dict = resultSet.resultDictionary() as! [String : String]
            }
        }
        return dict as Dictionary<String, String>
    }
}

字符串
SidePanelVC.swift

import UIKit

class SidePanelVC: UIViewController,UITableViewDataSource,UITableViewDelegate{
    @IBOutlet weak var lblWelcomeMsg: UILabel!
    override func viewDidLoad() {
        self.setUserProfile()
    }
    func setUserProfile() {
        let userProfile = ModelManager.getInstance().getUserProfile()
        let userName:String = userProfile["FullName"] ?? "empty"
        lblWelcomeMsg.text = userName
    }
}

a64a0gku

a64a0gku3#

使用FMDB pod或github中的类。使用下面的代码进行数据库设置。
Github链接(Pods):https://github.com/ccgus/fmdb

import FMDB

let shared: DBManager = DBManager()

class DBManager: NSObject { 

     //Variables..

     var db = FMDatabase()
     var databasePath = String()

    override init()
    {
       super.init()
    
      let success:Bool
      let fileManager = FileManager.default
      success = fileManager.fileExists(atPath: dbPath().0)

      if !success {
        let databasePathFromApp = Bundle.main.path(forResource: "Databasename", ofType: "db")
        do {
            try fileManager.copyItem(atPath: databasePathFromApp!, toPath: dbPath().0)
        } catch let error as NSError
        {
            if isPrintValue
            {
                print("Error: \(error.localizedDescription)")
            }
        }
    }
    db = FMDatabase.init(path: dbPath().0)
    db.open()
    print("DB Path_\(dbPath().0)")
    if db.open(){
        //print("DB Open")
    }else{
       // print("DB Close")
    }
}

func dbPath() -> (String, URL)
{
    let documentURl = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL.fileURL(withPath: documentURl)
    let fileurl = url.appendingPathComponent("Databasename.db")
    let filePath = fileurl.path as String
    return (filePath, url)
}

  func closeDB() -> Void
  {
    db.close()
  }

  deinit {
  }
}

字符串

相关问题