【问题标题】:String interpolation of a string stored in a variable存储在变量中的字符串的字符串插值
【发布时间】:2021-08-01 10:09:11
【问题描述】:

我正在尝试使用 JavaScript 中的动态“WHERE”条件为 Amazon Athena 准备一些 SQL 查询。查询保存在另一个文件中的一个变量上。如何为其添加自定义 WHERE 条件?

我想要实现的伪代码,

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = ?';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1,['Jane']; 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'

任何人都可以向我建议一个正确的方法来做到这一点。我目前的解决方案发布在下面。

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = {stringToReplace}';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1.replace("{stringToReplace}", "'Jane"); 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'

【问题讨论】:

  • 请只使用准备好的语句。无需手动向SQL injection 敞开心扉
  • @VLAZ 感谢您的评论。你能解释一下准备好的陈述吗?我正在准备的查询不是针对 MYSQL/MSSQL,而是针对亚马逊 Athena。
  • 嗨,@LawrenceCherone,我正在尝试向Amazon Athena 执行此查询,因此上述方法对我不起作用。
  • 我猜你的意思是SELECT * FROM Contact

标签: javascript string interpolation


【解决方案1】:

我使用了一个小辅助函数,让你可以使用直接的 es6 字符串插值方式:

const template= (template, ctx) => {
   const script = new vm.Script('`' + template + '`')
   return script.runInNewContext(ctx)
}

const results = template('hello ${foo}', {foo:'jane'})

但是,如果你只需要做一个简单的插值,为什么不直接将 sql 导出为一个函数呢?

const queryFromFile1 = str => (`SELECT * Name FROM Contact WHERE Name = ${str}`)

const query = queryFromFile1('Jane')

【讨论】:

    【解决方案2】:

    如 cmets 中所述,您不应使用原始字符串处理 SQL 语句。

    但是,对于代码的非安全关键部分(例如,从组件道具中获取日期格式字符串),我更喜欢这样做:

    const stringProducer = (insert) => `This was inserted: ${insert}`;
    

    然后像这样使用:

    const string = stringProducer("foo");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2012-10-26
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      相关资源
      最近更新 更多