node.js
  • postgresql
  • node-postgres
  • 2016-05-19 37 views 2 likes 
    2

    我想通過列名稱爲的字典,從而避免在查詢本身內聲明列名(直接鍵入它們)。省略列名/直接將對象插入到node-postgres中


    假設我有一個表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(); 
        }); 
    

    如果有一種方法來只通過一本字典&我寧願把它從鍵推斷列名 - 如果有一個簡單的竅門,我想聽到它。

    E.g是這樣的:

    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(); 
        }); 
    

    回答

    2

    有在insert聲明鍵值值不支持,所以它不能與本地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' ] } 
    
    2

    的一個完整的例子與pg-promise做:

    const pgp = require('pg-promise')(/*options*/); 
    const cn = 'postgres://username:[email protected]: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') 
    
    +0

    感謝兄弟,這是我在尋找 – andrux90210

    相關問題