【问题标题】:node sql server insert data to a tabelnode sql server 向表中插入数据
【发布时间】:2018-10-30 19:05:22
【问题描述】:

我有一个网站,有一个表格我想获取发布数据(我已经做到了)并将其放入数据库中。

数据以 JSON 形式出现,如下所示:

{ name : "text" , ho : "text" , day : number , m : number } 

我也有一个 SQL server 表怎么有相同的列名含义:

  • Col1 = 名称 (nvarchar)
  • Col2 = ho (nvarchar)
  • Col3 = 天 (numeric)
  • Col4 = m (numeric)

我正在尝试使用 nodejs 和 mssql moudeul 将数据插入数据库。

我的代码如下所示:

    let config = {/*the info*/}
    //connect to the data base
    const pool = new sql.ConnectionPool(config , function(err){
    if(err) throw err;
    //get the keys and the values
    let colsName enter code here= Object.keys(theDataObj);
    let values = []
    for(let i = 0; i < colsName.length; i++){
         values.push(theDataObj[colsName[i]]);
         console.log(theDataObj[colsName[i]])//check to see what going in
   pool.request().query(`INSERT INTO ${tabelName}(${colsName}) VALUES (${values})` , function(err , result){
 if(err) throw err;
 console.log(result)
});
    }

});

每次我尝试运行此代码时,如果我更改内容都没关系,它会向我发送相同的错误:

没有列名 ${values[0]}

我的意思是这句话的价值。

数组中的值在位置 0 或有时为 1。

如果有人知道我可以将数据插入到 sql 表中的方法,它会救我。在doc 中对此没有很好的扩展。

当我想将这样的数据添加到表中时,我来自 python 背景

【问题讨论】:

    标签: python node.js sql-server node-mssql


    【解决方案1】:

    从 SQL Server 2016 开始提供原生 json 支持(更多信息here)。

    如果您使用的是 SQL Server 2016(或更高版本),您可以将整个 json 传递给 SQL Server,并使用 openjson 和子句 with 读取存储在 json 中的数据(这将让您指定你的json)。然后你可以插入到你的表中:

    declare @json nvarchar(max) = '{ "name" : "text" , "ho" : "text" , "day" : 1 , "m" : 10}'
    
    insert into YOUR_TABLE
    select  Col1, Col2, Col3, Col4 
    from openjson(@json)
    with(   
        Col1 nvarchar(50) '$.name' ,  
        Col2 nvarchar(50) '$.ho',  
        Col3 numeric      '$.day',  
        Col4 numeric      '$.m'  
    ) 
    

    请注意,您的 json 无效:您在键名周围缺少引号。您的 json 的有效版本应该是:

    { "name" : "text" , "ho" : "text" , "day" : number , "m" : number } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      相关资源
      最近更新 更多