简体   繁体   English

node.js-从mysql查询中调用javascript变量

[英]node.js - Call javascript variable from within mysql query

I am trying to call javascript variables from within the mySQL query. 我正在尝试从mySQL查询中调用javascript变量。 The lines are executed with node.js environment, using syntax [node (filename)]. 这些行在node.js环境中使用语法[node(filename)]执行。 I understand that I could potentially do this query in 2 steps, by first query the value of min_value, and then query the max_value. 我了解我可以分两步执行此查询,方法是先查询min_value的值,然后查询max_value。

Can the request be executed in one mySQL query? 可以在一个mySQL查询中执行请求吗?

Preferably I would like to keep the code structure with vanilla js and mySQL, without adding node.js-specific commands, nor needing to load extra packages. 最好是,我希望保留香草js和mySQL的代码结构,而无需添加特定于node.js的命令,也无需加载额外的程序包。

Javascript variables: JavaScript变量:

let min_value = 100;
let max_value = 300;

This works: 这有效:

sql = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN 100 and 300
ORDER BY acronym;
`;

This does not works: 这不起作用:

sql = `
 SELECT
   acronym,
   salaries
 FROM 
   employees
 WHERE
   salaries BETWEEN ($min_value) and ($max_value)
ORDER BY acronym;
`;

Try using Template Literals , with the ${variable} placeholder syntax: 尝试使用${variable}占位符语法使用Template Literals

 let min_value = 100; let max_value = 300; let sql1 = ` SELECT acronym, salaries FROM employees WHERE salaries BETWEEN (${min_value}) and (${max_value}) ORDER BY acronym; `; let sql2 = ` SELECT acronym, salaries FROM employees WHERE salaries BETWEEN ${min_value} and ${max_value} ORDER BY acronym; `; console.log(sql1); console.log(sql2); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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