Escape single quote in Postgres query inside node js app

7.7k views Asked by At

Here is a line from my node js code:

var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite")  VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')'

I want to insert single quotes before JSON.stringify(req.body.favourite). But i'm unable to escape the single quotes. I can't debug the issue since I'm uploading the code to a predix cloud server Any idea how to achieve that?

2

There are 2 answers

0
e4c5 On BEST ANSWER

Why don't you use prepared statements?

var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite")  VALUES ($1, $2)';
client.query(qry, [ req.body.user, JSON.stringify(req.body.favourite])'
1
Rocha On

You could also use template literals to build your query

Template literals which use the back-tick character Check main answer here

alert(`Use "double" and 'single' quotes in the same string`);
alert(`The escape the \` back-tick character in a string`);

Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.