2

I'm trying to read from my database using the sqlite3 package in NodeJS. In the code I have:

 var sqlite = require('sqlite3');
 var db = new sqlite.Database('myDatabase.db');

 var someUserInput = 'Some given id by the user';

 db.all(
     'SELECT * FROM MyTable WHERE userId="' + someUserInput + '"',
     function(err, rows) { /* Do something here */});

Instead of directly adding the user input, I would like to be able to prepare the statement properly, in order to avoid any malicious input from the user.

I have tried:

 db.prepare('SELECT * FROM MyTable WHERE userId=?', someUserInput).sql

But that still gives me:

'SELECT * FROM MyTable WHERE userId=?'

With no replacement from the input.

Thanks!

1
  • In SQLite, query parameters are passed directly to the SQL executor; they don't get textually substituted into the query. Commented Dec 17, 2015 at 16:22

1 Answer 1

1

I think you almost had it with your db.all call. Try passing your user value as a parameter:

db.all(
     'SELECT * FROM MyTable WHERE userId=?',
     someUserInput,
     function(err, rows) { /* Do something here */});

Source: https://github.com/mapbox/node-sqlite3/wiki/API#databaseallsql-param--callback

Sign up to request clarification or add additional context in comments.

1 Comment

Totally missed that when searching the documentation, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.