Reputation: 129
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())")
}
}
Upvotes: 2
Views: 3830
Reputation: 437452
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() {
defer { contactDB.close() }
do {
try contactDB.executeUpdate("UPDATE Darood SET count=? WHERE title=?", values: [counter, title])
} catch {
print(error)
}
} 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.
Upvotes: 6
Reputation: 2698
I'm sure you are using myTitle
as option value, if it is optional
try this
let querySQL = "UPDATE Darood SET count='\(localCounter)' WHERE title='\(myTitle!)'"
OR make myTitle
mandatory field and assign empty ("")
as default value.
and then
let querySQL = "UPDATE Darood SET count='\(localCounter)' WHERE title='\(myTitle)'"
Upvotes: 0