简体   繁体   中英

How to write multiline MySQL queries in node.js using backticks?

I have a problem trying to write MySQL queries inside my node.js application. When writing a large query I need to split the code into various lines, so I need to use backticks to write a JavaScript string. The point is that inside my MySQL query I also need to use backticks as part of the query, like this:

SELECT `password` FROM `Users`

So the code for executing the query in node.js should look like this:

database.query(`
  SELECT `password` 
  FROM `Users`
`);

but the code doesn't work because the backticks of the query are interpreted as backticks of the string literal. I could concatenate several string literals using single or double quotes like this:

database.query( 
  'SELECT `password` ' +
  'FROM `Users`'
);

but I tried and it becomes a mess very quickly. I also tried to use a different approach using a special char as backticks replacement and replacing it with backticks with the replaceAll() function like this (inspired by MSSQL):

`SELECT [password]
FROM [Users]`.replaceAll('[', '`').replaceAll(']', '`');

So my question is: is there a way to write a multiline MySQL query without escaping the query backticks or without concatenating several single or double quotes string literals?

I prefer to just not use backticks in my MySQL queries. If you still need quotes around a table name, you can try setting ANSI_QUOTES to allow using " instaead: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi_quotes

If that doesn't work, you might prefer to just escape the backticks: Template literals with nested backticks(`) in ES6

I try to avoid backticks in queries. It is not ANSI SQL, it litters the code and in 99.9% of cases they are not needed. Even if you use some keywords as column names, in most cases it simply works, despite being colored differently in IDE.

If I have to use them, I escape them with backslash, which, for the rare case it is needed, is not too bad.

Lastly, if you really don't want to use string literals,

const sql = [
 "SELECT *",
 "FROM mytable",
 "WHERE x=0"
].join("\n");

still works just fine.

You could use a different character (that isn't used elsewhere in the query) and replace it with backticks afterwards. For example, # :

const query = `
SELECT #password#
FROM #Users#
`
  .replaceAll('#', '`')

Another option would be to import the query from a text file ( not in JavaScript syntax), and import it somehow:

password-query.txt:

SELECT `password` 
FROM `Users`
const query = fs.readFileSync('./password-query.txt', 'utf-8');
// ...
database.query(query)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM