Node-sqlite3: can we pass param in select * from table in?

Created on 22 Oct 2015  路  4Comments  路  Source: mapbox/node-sqlite3

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)
})
question

Most helpful comment

Using string interpolation:

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

All 4 comments

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)
})

+1 for supporting "IN"

+1锛宯eed "IN" supoort

Using string interpolation:

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

milu2003 picture milu2003  路  16Comments

coolaj86 picture coolaj86  路  28Comments

Thavaprakash picture Thavaprakash  路  31Comments

springmeyer picture springmeyer  路  29Comments

Aminadav picture Aminadav  路  16Comments