Anonymous Entity
Anonymous Entity

Reputation: 3350

Wildcard in nodejs sqlite3

How can I use wildcards with a parameter in the nodejs version of sqlite3? Code:

let db = new sqlite.Database(...)
const param = 'x'
db.all('select * from mytable where name like "%?%"', [param], (err, rows) => {
    ...

This results in

SQLITE_RANGE: column index out of range

Some suggests adding the wilcards into the query string like this:

const param = '%' + 'x' + '%'

But that seems to result in literally searching for name like "%x%", instead of using wildcards. I know the query I'm trying to run is correct because it returns the expected rows in the sqlite3 cli. How can I achieve the same thing in javascript?

Upvotes: 0

Views: 515

Answers (2)

MEDZ
MEDZ

Reputation: 2295

You need to include %% in the parameter and drop the double quotation marks:

const search = 'x';
const param = '%' + search + '%';
db.all('select * from mytable where name like ?', [param], (err, rows) => {

Upvotes: 3

Sardorjon Vakkosov
Sardorjon Vakkosov

Reputation: 270

You can use wildcards within parameters:

let db = new sqlite.Database(...)
const param = {$name: '%Alice%'}
db.all('select * from mytable where name like $name', param, (err, rows) => {

Upvotes: 2

Related Questions