代码之家  ›  专栏  ›  技术社区  ›  user3690467

Node.js-允许命名替换的sqlstring替代方案

  •  2
  • user3690467  · 技术社区  · 7 年前

    这个 sqlstring 节点模块允许使用有序数组创建查询。因此,如果我有一个模板查询,如:

    sqlstring.format('Select * from users where id = ?', ['my_id'])
    

    Select * from users where id = 'my_id'
    

    然而,在这里我需要记住问号的顺序,所以如果同一个东西在多个地方,那就成了一件麻烦事。是否有其他方法允许我执行以下操作:

    sqlstring.format('Select :id + :foo as bar from users where id = :id', {id: 1, foo: 3})
    

    这将成为:

    Select 1 + 3 as bar from users where id = 1
    

    我知道 knex QueryBuilder可以这样做,但我不想只为QueryBuilder安装整个knex。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Queenvictoria    5 年前

    你可以用 mysql2 支持该格式的包:

    Named placeholders

    namedPlaceholders配置值或查询/执行时间选项。命名 占位符是否转换为未命名?在客户端(mysql协议)上 不支持命名参数)。如果引用参数 时代。

    connection.config.namedPlaceholders = true;
    connection.execute('select :x + :y as z', {x: 1, y: 2}, function (err, rows) {
         // statement prepared as "select ? + ? as z" and executed with [1,2] values
         // rows returned: [ { z: 3 } ]
     });
    
    connection.execute('select :x + :x as z', {x: 1}, function (err, rows) {
         // select ? + ? as z, execute with [1, 1]
    });
    
    connection.query('select :x + :x as z', {x: 1}, function (err, rows) {
         // query select 1 + 1 as z
    });
    
    推荐文章