【问题标题】:How to use existing SQLite in swift 3? (FMDB)如何在 swift 3 中使用现有的 SQLite? (FMDB)
【发布时间】:2017-04-26 05:46:05
【问题描述】:

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

【问题讨论】:

    标签: ios swift sqlite fmdb


    【解决方案1】:

    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 时避免编写 SQL。请参阅README.md 了解更多信息。

    【讨论】:

    • 这是迄今为止我测试过的最好的!非常容易使用。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 2011-10-21
      相关资源
      最近更新 更多