Search code examples
swift3xcode8fmdb

How to get two data from FMDB and return a String combined two of them in swift?


I have two records in my database, 'FirstName and LastName and I wanna get two of them then return a FullName, showing FullNames in tableView. Using Swift3 and Xcode8.2.1, FMDB here's the func of getFullName

    func getFullName() -> String{

    StudentDataBase.getInstance()
    sharedInstance.database!.open()

    let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT FirstName, LastName FROM Student_info", withArgumentsIn: nil)
    let fullName  = (result?.string(forColumn: "FirstName"))! + " " + (result?.string(forColumn: "LastName"))!
    return fullName
}

sharedInstance is a global one, StudentDataBase is s singleton class:

class StudentDataBase : NSObject {

var database: FMDatabase? = nil
var pathToDB: String!

class func getInstance() -> StudentDataBase{

    if((sharedInstance.database) == nil)
    {
        sharedInstance.database = FMDatabase(path: Utility.getPath("data.db"))
    }
    return sharedInstance
}

and my Student.swift goes like this:

import UIKit

//the model class to fetch the data from data.db
class Student : NSObject {

    var studentID: String = String()
    var fstName: String = String()
    var lstName: String = String()
    var phoneNum: String = String()

}

I got a thread goes like this enter image description here Thank you so much if anyone can help

After editing the Query into

    let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT ifnull(FirstName,'') as FirstName, ifnull(LastName,'') as LastName FROM Student_info", withArgumentsIn: nil)

There's another error in combining them into one String: enter image description here


Solution

  • You are getting this crash because either you are getting nil for FirstName or LastName, and you can use ifnull with your select query and return empty string if it is nil. So change your query like this way.

    let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT ifnull(FirstName,'') as FirstName, ifnull(LastName,'') as LastName FROM Student_info", withArgumentsIn: nil)
    

    Note: You haven't added WHERE clause with query so that this will give you all the records form Student_info table also it is batter if you check result.next() to confirm result contains records or not.