V
V
valentine112016-01-22 13:14:25
MySQL
valentine11, 2016-01-22 13:14:25

SQL queries in JS code, escape special characters or not?

Good afternoon!
I automate the testing process with Node.js and Selenium-wd.
Before and after test blocks, queries to the database are performed (creating preconditions or clearing the database).
Requests are stored in variables in string form.
There is a problem with single quotes.
Let me explain with an example:

needForReg = 'INSERT INTO `billing_payment_gateway` (--\
             `id`, `name`, `route`, `description`, `is_active`, `is_deleted`--\
       ) VALUES (--\
       1, 'interkassa', 'InterkassaGateway', '', 1, 0);'

Having reached 'interkassa' the line will be interrupted and any nonsense will follow.
So far, I solved the problem by escaping quotes:
needForReg = 'INSERT INTO `billing_payment_gateway` (--\
             `id`, `name`, `route`, `description`, `is_active`, `is_deleted`--\
       ) VALUES (--\
       1, \'interkassa\', \'InterkassaGateway\', \'\', 1, 0);'

But this is only part of the request, and there are requests that are much longer, escaping quotes is tiring and generally does not look very good.
You can solve the problem by simply enclosing the query string in double quotes. and I like this idea.
needForReg = "INSERT INTO `billing_payment_gateway` (--\
             `id`, `name`, `route`, `description`, `is_active`, `is_deleted`--\
       ) VALUES (--\
       1, 'interkassa', 'InterkassaGateway', '', 1, 0);"

But is it correct? What about security in this case? Or maybe there are solutions for automatic escaping, if there is no way without it? I'm still swimming in this all, knowledge is very superficial.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-01-22
@bingo347

Double quotes differ from single quotes only in the absence of newlines (you cannot escape a newline).
It is quite possible to put queries into separate files with the .sql extension - this is how the IDE will highlight the syntax;
you can read files into memory when the application starts in synchronous mode, and so that there are not many files, you can implement a parser in order to keep several queries in one file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question