我想通过喜欢查询并尝试这样:
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)
}
但它不起作用。
答案 0 :(得分:1)
试试这个:
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)
}
答案 1 :(得分:0)
只需在sql语句中传递参数?并使用SQL通配符包装传递的值,如下所示:
let name = "%pp%"
...
var queryString = "select * from products where name like ? and deleted = 0 order by id desc"
原因在于SQLite,并且可能在每个其他SQL引擎中,参数是一个包含其值和类型信息的完整实体。因此,永远不需要在{(1)}之类的引号(')中包装参数,这实际上是错误的做法。
另外'%?%'
运算符只需要一个字符串表达式作为操作数,如果需要可能包含SQL通配符。因此,您只需要创建一个带有嵌入式通配符(%,_等)的字符串表达式,并在需要时将其传递给您的语句。
希望它有所帮助。
答案 2 :(得分:0)
它对我有用(swift 4,Xcode 9):
let texto_like : String = "%\(texto)%"
let sql = "select * from TABLE where MY_COLUMN like ? COLLATE NOCASE"