Node.js Javascript承诺迭代/包含动态数量的参数

Node.js Javascript承诺迭代/包含动态数量的参数,node.js,sql-server,promise,azure-sql-database,tedious,Node.js,Sql Server,Promise,Azure Sql Database,Tedious,我使用mssql npm模块和繁琐的驱动程序从节点服务器读/写Azure Sql数据库 我找到的所有示例都提供了一个硬编码的示例,用于查询是读取还是写入记录,如下所示: var insertRecordIntoTable = function (callback) { sql.connect(dbConfig).then(pool => { return pool.request() .input('ID', sql.Int, 210) .

我使用mssql npm模块和繁琐的驱动程序从节点服务器读/写Azure Sql数据库

我找到的所有示例都提供了一个硬编码的示例,用于查询是读取还是写入记录,如下所示:

var insertRecordIntoTable = function (callback) {

  sql.connect(dbConfig).then(pool => {

     return pool.request()
        .input('ID', sql.Int, 210)
        .input('Name', sql.NVarChar, "John Doe")
        .input('EmailAddress', sql.NVarChar, "test@test.com")
        .query("INSERT INTO Accounts (ID, Name, EmailAddress) VALUES (@ID, @Name, @EmailAddress)")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}
var insertRecordIntoTable = function (jsonRecord, tableName, callback) {

  let arrKeys = jsonRecord.allKeys();
  let columnNames = getCommaSeparatedColumnNames(arrKeys); 
  let valuePlaceholders = getValuePlaceholdersForSql(arrKeys);

  sql.connect(dbConfig).then(pool => {

     return pool.request()

        // how do I write something like this so that dynamic number of fields and values get populated in the query inside this promise.
        // I'm open to methods without promise as well.

        for(let x=0; x < arrKeys.length; x++){

           let key = arrKeys[x];

           // .input('ID', sql.Int, 210)
           .input(key, getTypeForKey(key, tableName), jsonRecord[ key ] )

        }

        .query("INSERT INTO " + tableName + " (" + columnNames + ") VALUES (" + valuePlaceholders + ")")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}

function getTypeForKey(key){. // looks up table schema and returns keyType }

function getCommaSeparatedColumnNames(arrKeys){  return arrKeys.join(", "); }

function getValuePlaceholdersForSql(arrKeys){   // write code to append '@' before every key and then join using comma's and return that string }
显然,我想编写一个标准方法,将记录写入数据库中的任何表

现在,我可以获取每个表的结构,并使用它从jsonRecord中的键中找到每个字段的数据类型,并编写如下内容:

var insertRecordIntoTable = function (callback) {

  sql.connect(dbConfig).then(pool => {

     return pool.request()
        .input('ID', sql.Int, 210)
        .input('Name', sql.NVarChar, "John Doe")
        .input('EmailAddress', sql.NVarChar, "test@test.com")
        .query("INSERT INTO Accounts (ID, Name, EmailAddress) VALUES (@ID, @Name, @EmailAddress)")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}
var insertRecordIntoTable = function (jsonRecord, tableName, callback) {

  let arrKeys = jsonRecord.allKeys();
  let columnNames = getCommaSeparatedColumnNames(arrKeys); 
  let valuePlaceholders = getValuePlaceholdersForSql(arrKeys);

  sql.connect(dbConfig).then(pool => {

     return pool.request()

        // how do I write something like this so that dynamic number of fields and values get populated in the query inside this promise.
        // I'm open to methods without promise as well.

        for(let x=0; x < arrKeys.length; x++){

           let key = arrKeys[x];

           // .input('ID', sql.Int, 210)
           .input(key, getTypeForKey(key, tableName), jsonRecord[ key ] )

        }

        .query("INSERT INTO " + tableName + " (" + columnNames + ") VALUES (" + valuePlaceholders + ")")
  }).then(result => {
     console.dir(result)
     callback(result);
  }).catch(err => {
     // ... error checks
     console.log("Error occured: " + err);
     callback(err);
  });

}

function getTypeForKey(key){. // looks up table schema and returns keyType }

function getCommaSeparatedColumnNames(arrKeys){  return arrKeys.join(", "); }

function getValuePlaceholdersForSql(arrKeys){   // write code to append '@' before every key and then join using comma's and return that string }
我相信node.js写入SQL是一个相当常见的功能,可能有更好的方法来实现我在这里尝试的功能。请随意选择不同的路线


尽管我应该说我更喜欢mssql而不是单调乏味的软件包。在过去几个小时内浏览了文档之后,它的功能似乎更好。

如果您想在不创建所有查询的情况下与数据库交互,可以使用查询生成器(如knex)将数据作为对象进行管理:

knex('Accounts').insert({ID: 210, Name: "John Doe", EmailAddress: "test@test.com"})
类似于:

insert into `Accounts` (`EmailAddress`, `ID`, `Name`) values ('test@test.com', 210, 'John Doe')

我还看到你在检查类型。如果您需要验证,也许我喜欢的完整ORM是一个不错的选择。

执行此操作的库通常称为ORM。如果你搜索ORM Node.js,我希望你能找到你需要的。谢谢@Hogan。我知道这一定有原因,只是不知道该去哪里找。我将研究Sequalize和类似的东西,并更新它。用现代语言编写自己的ORM也很容易——我用C写了一个,可以容纳150行。我一直在计划制作一个版本的节点,但没有机会。如果您有兴趣将其用作模板,请参阅以下开源代码:谢谢@Hogan。我看了一下,看起来不错。我看看能否在下个月再谈这件事。有可交付成果,这会让我在接下来的几周里忙个不停。谢谢@Rashomon。这两个看起来是不错的选择。我将研究它们并更新它们。