node-sqlite3 icon indicating copy to clipboard operation
node-sqlite3 copied to clipboard

can we pass param in select * from table in?

Open angelochen960 opened this issue 11 years ago • 5 comments

Hi, this works:

db.get("select * from sample where number in ( '0136', '5431', '5448', '0136' )", function(err, rslt) {
    console.log(rslt)
})

but this won't, any way to pass parameters into query in situations like this?

var sel = [ '0136', '5431', '5448', '0136' ]

db.get("select * from sample where number in ? ",  sel, function(err,  rslt) {
    console.log(rslt)
})

angelochen960 avatar Oct 22 '15 06:10 angelochen960

Unfortunately this doesn't work, values bound to parameters have to correspond to SQLite types: Strings, Numbers, Booleans, null. Also, sel is an array and gets interpreted as a list of parameter values rather than one value. If you know the length of sel you can have a statement like:

select * from sample where number in (?, ?, ?)

If sel has a variable length you'll have to stick together a valid statement somehow:

var sel = [5431, 5448]

function inParam (sql, arr) {
  return sql.replace('?#', arr.map(()=> '?' ).join(','))
}

db.all(inParam('select * from sample where number in (?#)', sel), sel, function(err, rslt){
  console.log(rslt)
})

lvivier avatar Oct 29 '15 17:10 lvivier

+1 for supporting "IN"

rns4731 avatar Apr 25 '16 23:04 rns4731

+1,need "IN" supoort

Houfeng avatar Jun 28 '16 06:06 Houfeng

Using string interpolation:

db.get(`select * from sample where number in (${sel.map(_ => '?')})`, sel, function(err, rslt) { console.log(rslt) })

mrvalb avatar Jun 25 '18 16:06 mrvalb

Closing as duplicate of https://github.com/TryGhost/node-sqlite3/issues/762 🙂

daniellockyer avatar Apr 15 '22 09:04 daniellockyer