Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quote in Postgres query inside node js app

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?

like image 556
iJade Avatar asked Jan 19 '17 13:01

iJade


2 Answers

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.

like image 45
Rocha Avatar answered Sep 30 '22 10:09

Rocha


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])'
like image 133
e4c5 Avatar answered Sep 30 '22 10:09

e4c5