Skip to content

Instantly share code, notes, and snippets.

@identity2
Created June 8, 2019 05:16
Show Gist options
  • Save identity2/5fb8e50fba030358bfff3fd5fbc61198 to your computer and use it in GitHub Desktop.
Save identity2/5fb8e50fba030358bfff3fd5fbc61198 to your computer and use it in GitHub Desktop.
search contact by id
func searchContactByID(_ id: Int) -> Contact? {
let queryString = "SELECT * FROM Contact WHERE ID = \(id)"
// Execute query and save the results.
let queryResults: FMResultSet? = mainDB?.executeQuery(queryString, withArgumentsIn: nil)
// Check if there are results.
if queryResults?.next() == true {
let contactName = queryResults!.string(forColumn: "Name")
let contactPhone = Int(queryResults!.int(forColumn: "Phone"))
let contactCity = queryResults!.string(forColumn: "City")
return Contact(id: id, name: contactName, phoneNumber: contactPhone, city: contactCity)
}
// No matching results.
return nil
}
func searchContactByName(_ name: String) -> [Contact] {
let queryString = "SELECT * FROM Contact WHERE Name = \(name)"
let queryResults: FMResultSet? = mainDB?.executeQuery(queryString, withArgumentsIn: nil)
// Save the results into an array.
var results = [Contact]()
while queryResults?.next() == true {
let contactID = Int(queryResults!.int(forColumn: "ID"))
let contactPhone = Int(queryResults!.int(forColumn: "Phone"))
let contactCity = queryResults!.string(forColumn: "City")
// Append the result to the results array.
results.append(Contact(id: contactID, name: name, phoneNumber: contactPhone, city: contactCity))
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment