【问题标题】:Omiting column names / inserting objects directly into node-postgres省略列名/将对象直接插入 node-postgres
【发布时间】:2017-06-22 06:13:03
【问题描述】:

我想将列名作为键的字典传递,从而避免在查询本身中声明列名(直接键入它们)。


假设我有一个表 User 有 2 个列名:

  • idUser(INT)
  • fullName(VARCHAR)

要使用node-postgres 创建记录,我需要在查询中声明列名,如下所示:

    var idUser   = 2;
    var fullName = "John Doe";
    var query = 'INSERT INTO User(idUser, age) VALUES ($1, $2)';

    database.query(query, [idUser, fullName], function(error, result) {
      callback(error, result.rows);
      database.end();
    });

如果有一种方法可以传递字典并让它从键中推断列名,我更愿意 - 如果有一个简单的技巧,我想听听。

例如这样的:

    var values = {
      idUser  : 2,
      fullName: "John Doe"
    };
    var query = 'INSERT INTO User VALUES ($1)';

    database.query(query, [values], function(error, result) {
      callback(error, result.rows);
      database.end();
    });

【问题讨论】:

    标签: node.js postgresql node-postgres


    【解决方案1】:

    使用pg-promise 的完整示例:

    const pgp = require('pg-promise')(/*options*/);
    const cn = 'postgres://username:password@host:port/database';
    const db = pgp(cn);
    
    const values = {
        idUser: 2,
        fullName: 'John Doe'
    };
    
    // generating the insert query:
    const query = pgp.helpers.insert(values, null, 'User');
    //=> INSERT INTO "User"("idUser","fullName") VALUES(2,'John Doe')
    
    db.none(query)
        .then(data => {
            // success;
        })
        .catch(error => {
            // error;
        });
    

    如果专注于高性能,它会变成这样:

    // generating a set of columns from the object (only once):
    const cs = new pgp.helpers.ColumnSet(values, {table: 'User'});
    
    // generating the insert query:
    const query = pgp.helpers.insert(values, cs);
    //=> INSERT INTO "User"("idUser","fullName") VALUES(2,'John Doe')
    

    【讨论】:

    • 谢谢兄弟,这是我要找的
    【解决方案2】:

    insert语句中不支持key-value值,所以不能用原生sql做。

    但是,node-postgres extras 页面提到了多个 sql 生成工具,例如,Squel.js 参数可用于以非常接近您正在寻找的方式构造 sql:

    squel.insert()
        .into("User")
        .setFieldsRows([
          { idUser: 2, fullName: "John Doe" }
        ])
        .toParam()
    
    // => { text: 'INSERT INTO User (idUser, fullName) VALUES (?, ?)',
    //      values: [ 2, 'John Doe' ] }
    

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 2014-07-23
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2015-10-27
      相关资源
      最近更新 更多