4

What is the recommended way to open and close a sqlite db connection with Swift + FMDB?

I'm following this tutorial which suggests that you should open and close a database like:

let db = FMDatabase(path: databasePath as String)
if db.open() {
    //do stuff
    db.close()

Closing the db outside of a finally block would be a red flag in other languages I've used. I know swift/iOS exception handling is different than most languages and dev environments. But I'm still concerned that this is still a really unsafe way to close the database connection.

Is this method of closing a db actually safe & recommended?
Should I be using something like SwiftTryCatchFinally instead?

let db = FMDatabase(path: databasePath as String)
SwiftTryCatch.try({
    connection = db.open()
    if connection {
        //do stuff
    }
}, catch: {

}, finally: {
    if connection {
        db.close()
    }
})

iOS exception handling is so foreign to me :P

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80

1 Answers1

0

This is the approach I take which might give you an insight. I have the database calls in the programs but the table methods (create, add, update) are in a class that is called multiple times as and when required.

So to create a database I call, in this case when a button is pressed:

@IBAction func buttonCreateTable(sender: AnyObject) {
    var locationRecord: LocationRecord = LocationRecord()
    var isCreated = DatabaseFunctions.instance.createLocationTable()
    if isCreated {
        NSLog("Locations Database Created")
    } else {
        NSLog("Locations Database Not Created")
    }
}

The class, DatabaseFunctions.swift, would read ...

import UIKit
let sharedInstance         = DatabaseFunctions()
class DatabaseFunctions: NSObject {
var database: FMDatabase? = nil

class var instance: DatabaseFunctions {
    sharedInstance.database = FMDatabase(path: Utilities.getPath("yourDatabase.sqlite"))
    var path = Utilities.getPath("yourDatabase.sqlite")
    return sharedInstance
}



// yourTableFunctions *************************
func createLocationTable() -> Bool {
    sharedInstance.database!.open()
    let sqlStatement = "CREATE TABLE IF NOT EXISTS MYTABLE (ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP, TIMESTAMPLASTEDIT DATETIME DEFAULT CURRENT_TIMESTAMP, NAME TEXT, nil)"
    let isCreated = sharedInstance.database!.executeUpdate(sqlStatement, withArgumentsInArray:nil)
    sharedInstance.database!.close()
    return isCreated
}

}

The LocationsRecord is held separate in another swift, LocationInfo.swift, file like:

import UIKit

// Locations Class
class LocationRecord: NSObject {

var locationSelected : Int32         = Int32()
var locationRecordNo : Int32         = Int32()
var locationName: String             = String()

}

Edward Hasted
  • 3,201
  • 8
  • 30
  • 48
  • I don't understand how this relates to my question. The database connection will still not be closed if there is an error in any one of your creat, add, update, etc. functions. – Steven Wexler Jul 23 '15 at 19:01
  • Maybe I misread you. What you have to get right is for the sharedInstance.database!.open(), sharedInstance.database!.close() to work correctly. That way even if an instruction fails the table has been closed off correctly. What this example shows in the "if isCreated {..." you get a success/error message if it fails. That way you can focus in on the code until you have it right. As I say If I missed the point apologies and ignore. Best. – Edward Hasted Jul 23 '15 at 19:06