簡體   English   中英

如何在 FMDB 查詢 iOS Swift 4 中使用 Like with Text ?

[英]How to using Like with Text in FMDB query iOS Swift 4?

我想用like查詢並嘗試這樣:

let name = "pp" //apple

let db = openDB()
  do {
      var queryString = "select * from products where name like '%?%' and deleted = 0 order by id desc"
      let rs = try db.executeQuery(queryString, values:[name])
      var arr:Array<Product> = []
      while rs.next() {
      arr.append(parseProductDB(rs))
      }
      closeDB(db)
} catch {
      print("failed: \(error.localizedDescription)")
      closeDB(db)
}

但它不起作用。

試試這個:

let db = openDB()
do {
    var queryString =
    queryString = String(format:"select * from products where name like '%%%@%%' and deleted = 0 order by id desc",name)
    let rs = try db.executeQuery(queryString, values:nil)
    var arr:Array<Product> = []
    while rs.next() {
    arr.append(parseProductDB(rs))
    }
    closeDB(db)

} catch {
            print("failed: \(error.localizedDescription)")
            closeDB(db)
}

它對我有用(swift 4,Xcode 9):

let texto_like : String = "%\(texto)%"

let sql = "select * from TABLE where MY_COLUMN like ? COLLATE NOCASE"

只需在您的 SQL 語句中傳遞參數? 並用 SQL 通配符包裝您傳遞的值,如下所示:

let name = "%pp%"
...
var queryString = "select * from products where name like ? and deleted = 0 order by id desc"

原因是在 SQLite 中,並且可能在所有其他 SQL 引擎中,參數是一個完整的實體,包括其值和類型信息。 因此,像'%?%'這樣'%?%'引號 (') 中的參數從不需要,實際上是錯誤的做法。

同樣like操作符只需要一個字符串表達式,因為它的操作數可能包含 SQL 通配符(如果需要)。 因此,您只需要創建一個帶有嵌入通配符(%、_ 等)的字符串表達式,並在需要時將其傳遞給您的語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM