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

时间:2017-04-26 05:46:05

标签: ios swift sqlite fmdb

我想将(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
}

2 个答案:

答案 0 :(得分:3)

FMDB是一个很棒的Objective-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。有关详细信息,请参阅README.md

答案 1 :(得分:2)

这是swite中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
    }
}