From 490a124cbf929ef980ac61b18db6ad5dc0b35c9e Mon Sep 17 00:00:00 2001 From: Alexandre Colucci Date: Tue, 14 May 2019 08:59:41 +0200 Subject: [PATCH] #530: Wrong number of statement arguments with "like '%?%'" Add "? as a parameter" in the "Good to Know" section to explain how to build like pattern like '%?%'. --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 57efc30f0..eee77fd76 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,7 @@ Documentation #### Good to Know - [Avoiding SQL Injection](#avoiding-sql-injection) +- [? as a parameter](#-as-a-parameter) - [Error Handling](#error-handling) - [Unicode](#unicode) - [Memory Management](#memory-management) @@ -7470,6 +7471,26 @@ try dbQueue.write { db in ``` +## ? as a parameter + +SQLite only understands `?` as a parameter when it is a placeholder for a whole value (int, double, string, blob, null). +On the other side, the `?` in `'%?%'` is just a character in the `'%?%'` string value: it is not a query parameter, and is not processed in any way. +You need to take this into consideration for queries like: + +```sql +SELECT * FROM students where name like '%Robert%'; +``` + +To provide the parameter, you can let SQLite build the like pattern using the string concatenation operator `||`: + +```swift +let name = textField.text +try dbQueue.read { db in + try db.execute(sql: "SELECT * FROM students where name like '%' || ? || '%'", arguments: [name]) +} +``` + + ## Error Handling GRDB can throw [DatabaseError](#databaseerror), [PersistenceError](#persistenceerror), or crash your program with a [fatal error](#fatal-errors).