iosswiftsqlitefmdb

How to use existing SQLite in swift 3? (FMDB)


I want to connect (Salary.db) to my iOS (Swift) project and get the data from the database?

First step, how can I connect existing database in 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
}

Solution

  • FMDB is a wonderful Objective-C library, that has not been updated for Swift, and sometimes feels awkward in Swift.

    You may consider using a library like GRDB.swift which is written in Swift, robust, fast, and grants you the same features as 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 also allows you to avoid writing SQL when you don't want to. See the README.md for more information.