Search code examples
iosswiftsqlitefmdb

SQLite singleton class in Swift ( FMDB wrapper )


I am working on Swift singleton class to integrate SQLite easily ( Using FMDB wrapper class )

Simple methods to create database in directory, insert and fetch data.

Bridging support for FMDB Objective C usage in Swift.

let contactDB = FMDatabase(path: String(methodToCreateDatabase()!.absoluteString) )

if contactDB.open() {

    let insertSQL = strQuery

    let result = contactDB.executeUpdate(insertSQL,
                withArgumentsInArray: nil)

    if !result {
                print("Failed to add contact")
                print("Error: \(contactDB.lastErrorMessage())")
        return false
    } else {
        print("Contact Added")
                return true
    }
} else {
     print("Error: \(contactDB.lastErrorMessage())")
     return false
}

Solution

  • Swift singleton manager class to integrate SQLite easily and quickly.

    Source code - https://github.com/hasyapanchasara/SQLite_SingleManagerClass

    • SingleTonManager class

    • Swift language

    • Use of FMDB

    • Array return for select statement

    • Boolean flag for insert, update and delete statement

    Method to create database

    LocalDatabase.sharedInstance.methodToCreateDatabase()
    

    Method to insert, update and delete data

    if LocalDatabase.sharedInstance.methodToInsertUpdateDeleteData("INSERT INTO CONTACTS_TABLE (name, address, phone) VALUES ('Demo1', 'Demo2', 123)")
    {
        NSLog("Store Successfully.")
    }
    else
    {
        NSLog("Failled to store in database.")
    }
    

    Method to select data

    LocalDatabase.sharedInstance.methodToSelectData("SELECT * FROM CONTACTS_TABLE")