mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
Provide one example that lets Swift build the pattern and an example with the query interface. Then provide the second approach using the || operator.
This commit is contained in:
1 parent
7ed4b799b7
commit
3669fadecb
1 file changed
+23
-3
@@ -8659,12 +8659,32 @@ let players = try dbQueue.read { db in
|
||||
|
||||
What is important to understand here is that SQLite only interprets `?` as a parameter when it is a placeholder for a whole value (int, double, string, blob, null). In this incorrect query, `?` is just a character in the `'%?%'` string value: it is not a query parameter, and is not processed in any way. See [https://www.sqlite.org/lang_expr.html#varparam](https://www.sqlite.org/lang_expr.html#varparam) for more information about SQLite parameters.
|
||||
|
||||
To provide the parameter, one option is to let SQLite build the like pattern using the string concatenation operator `||`:
|
||||
To provide the parameter, one option is to let Swift build the pattern:
|
||||
|
||||
```swift
|
||||
let name = textField.text
|
||||
try dbQueue.read { db in
|
||||
try db.execute(sql: "SELECT * FROM students where name like '%' || ? || '%'", arguments: [name])
|
||||
let players: [Player] = try dbQueue.read { db in
|
||||
let pattern = "%\(name)%"
|
||||
return try Player.fetchAll(db, sql: "SELECT * FROM player WHERE name LIKE ?", arguments: [pattern])
|
||||
}
|
||||
```
|
||||
|
||||
This solution could also be used with the query interface:
|
||||
|
||||
```swift
|
||||
let name = textField.text
|
||||
let players: [Player] = try dbQueue.read { db in
|
||||
let pattern = "%\(name)%"
|
||||
return try Player.filter(Column("name").like(pattern)).fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Another option is to let SQLite build the like pattern using the string concatenation operator `||`:
|
||||
|
||||
```swift
|
||||
let name = textField.text
|
||||
let players = try dbQueue.read { db in
|
||||
try Player.fetchAll(db, sql: "SELECT * FROM player WHERE name LIKE '%' || ? || '%'", arguments: [name])
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in new issue
Block a user