FMDatabase + fast + query with undefined number of arguments

I am trying to send a request to FMDB through the Swift class.

It works:

self.database.executeQuery("SELECT * FROM foods WHERE id = ?", withArgumentsInArray:[anID]) 

because I used the executeQuery method (sql, withArgumentsInArray)

But I do not know how to use the classic method with the number of arguments undefined, and not with an array:

 self.database.executeUpdate(<#sql: String?#>, withVAList: <#CVaListPointer#>) 

I do not know how to write my arguments in withVAList.

+6
source share
3 answers

My solution was to create an FMDatabase wrapper:

 let success:Bool = FMDatabaseWrapper().executeUpdate(sql, food.ID?, food.name?) func executeUpdate(sql:String, _ arguments: AnyObject?...) -> Bool { return database.executeUpdate(sql, withArgumentsInArray:arguments as NSArray) } 

He works.

+5
source

The problem is that Swift cannot overload the function of the same name with a function that takes a variable number of arguments. Thus, given the “choice” between understanding your call to executeUpdate as the call to executeUpdate:withArgumentsInArray: and the call to executeUpdate:(NSString*)... , the latter never appears as an opportunity.

However, in reality there is no problem, because you never need to call this method. It does nothing but call executeUpdate:withVAList: which you can directly call directly using the built-in Swift getVaList function (see fooobar.com/questions/210751 / ... ).

Or even better, just go with using executeUpdate:withArgumentsInArray: If there are no arguments, just pass nil for the second parameter.

+2
source

If this helps, I created an elegant SQLite library, fully written in Swift, called SwiftData .

Some of its features:

  • Bind objects to SQL string
  • Transaction and savepoint support
  • Embedded Error Handling
  • Fully thread safe by default

It provides an easy way to make “changes” (for example, INSERT, UPDATE, DELETE, etc.):

 if let err = SD.executeChange("INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES ('Toronto', 2615060, 0, '1793-08-27')") { //there was an error during the insert, handle it here } else { //no error, the row was inserted successfully } 

and "queries" (e.g. SELECT):

 let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities") if err != nil { //there was an error during the query, handle it here } else { for row in resultSet { if let name = row["Name"].asString() { println("The City name is: \(name)") } if let population = row["Population"].asInt() { println("The population is: \(population)") } if let isWarm = row["IsWarm"].asBool() { if isWarm { println("The city is warm") } else { println("The city is cold") } } if let foundedIn = row["FoundedIn"].asDate() { println("The city was founded in: \(foundedIn)") } } } 

Along with many other features!

You can check it out here.

0
source

Source: https://habr.com/ru/post/970748/


All Articles