Muneeb Rehman Muneeb Rehman - 5 months ago 90
Swift Question

Unable to update a field in database FMDB using SWIFT

Here is my function in which I am trying to update a field

count
in my table. But it is not updating the value. Query is 100% fine as I have already tried it in external database software. May be I am using wrong function to execute my statement?

func updateLocalCount(var localCounter: Int)
{
let contactDB = FMDatabase(path: databasePath as String)
if contactDB.open()
{
let querySQL = "UPDATE Darood SET count='\(localCounter)' WHERE title='\(myTitle)'"
let results:FMResultSet? = contactDB.executeQuery(querySQL,
withArgumentsInArray: nil)
print(querySQL)
contactDB.close()
print("local count \(localCounter)")
}
else
{
print("Error: \(contactDB.lastErrorMessage())")
}
}

Rob Rob
Answer

You should use executeUpdate, not executeQuery for update queries. By calling executeQuery (and never calling next), you've simply prepared a query, but never performed it.

So, it might look like the following:

func updateLocalCount(counter: Int, title: String) {
    let contactDB = FMDatabase(path: databasePath as String)
    if contactDB.open() {
        do {
            try contactDB.executeUpdate("UPDATE Darood SET count=? WHERE title=?", values: [counter, title])
        } catch {
            print(error)
        }
        contactDB.close()
    } else {
        print("Error: \(contactDB.lastErrorMessage())")
    }
}

In an unrelated observation, you'll notice that, above, I used the ? placeholders in your SQL, not building SQL using string interpolation. You open yourself to a whole series of possible problems if you don't use placeholders.