javascript - 将对象数组分解为单独的变量以进行数据库存储(React、express、sql server)

标签 javascript sql sql-server reactjs express

我的reactjs应用程序中有一个存储的对象数组,当控制台记录时,它看起来像这样。

0: {answer: "yes↵", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}
1: {answer: "yes", question: "Does the keyboard tilt?", state: "Accepted"}
2: {answer: "Question declined But not a problem", question: "Is it possible to find a comfortable typing postion?", state: "Accepted"}
3: {answer: "yes", question: "Do you have a good keyboard technique?", state: "Accepted"}
4: {answer: "Question declined But not a problem", question: "Are the characters on the keyboard clear and readable?", state: "Accepted"}
5: {answer: "sgdfgdfgdf", question: "Is your mouse or other pointing device suitable to the task you're using it for?", state: "problem specified"}
6: {answer: "yes", question: "Is the mouse (or other pointing device) located sufficently close to you?  ", state: "Accepted"}
7: {answer: "sdfsdfsdfsd", question: "Is there support for your wrist and forearm when using the mouse(or other pointing device)", state: "Declined with soloution defined"}
8: {answer: "yes", question: "Does the mouse (or other pointing device) work smoothly at a speed that suits you?", state: "Accepted"}
9: {answer: "asdasdas", question: "Can you easily adjust the software settings for speed and accuracy of the pointer?", state: "Declined with soloution defined"}
10: {answer: "asdasdads", question: "Are the characters on your screen clear and readable?", state: "problem specified"}
11: {answer: "yes", question: "Is the text size on your screen confortable to read?", state: "Accepted"}
12: {answer: "asdasdasd", question: "Is the image on your screen free from flicker and jitter?", state: "Declined with soloution defined"}
13: {answer: "asdasdasd", question: "Is your screen's specification suitable for its intended use?", state: "problem specified"}
14: {answer: "yes", question: "Is the brightness and/or contrast on your screen adjustable?", state: "Accepted"}

这由答案、问题和状态组成(回答问题的状态不是 react 组件中的状态)

我想做的是将这些传递给express,以便我可以使用npm包mssql将它们上传到我的SQL数据库中。然而,由于这些都存储在数组中,我不确定如何将它们分开。

理想情况下,我希望将整个对象传递给 SQL 并将整个对象存储在数据库中,例如(伪代码)

insert into table where answer = answer and question = question and state = state

本质上,要与 SQL 一起使用,我将如何分解它们以便与我的后端一起使用,或者我可以使用特定的 SQL 存储过程传递整个对象。

create procedure StoreAnswers

@{answer_values}
as

INSERT INTO QuestionResponses                                         
(RUId, QuestionId, Date, QuestionWhenAnswered, QuestionResponse, Accepted, AssignedWorkStation )
VALUES
${answer_values}

编辑

存储过程

create procedure StoreAnswers(@Results varchar(max))
as begin
  insert into QuestionResponses(QuestionResponse, QuestionWhenAnswered, State)
         select substring(value, charindex('{answer: "', value) + 10,  charindex('", ', value, charindex('{answer: "', value) + 10) -  charindex('{answer: "', value) - 10) as answer, 
                substring(value, charindex('question: "', value) + 11, charindex('", ', value, charindex('question: "', value) + 11) - charindex('question: "', value) - 11) as question,
                substring(value, charindex('state: "', value) + 8,      charindex('"}', value,  charindex('state: "', value) + 8) -     charindex('state: "', value) - 8) as state
         from string_split(@Results, char(10))    
end;

如何从express npm传递到sql查询

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");

  let results = req.body.results;

  console.info(results);

  await sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();
    request.input("Results", sql.VarChar, results);
    // query to the database and get the records
    request.execute("dbo.StoreAnswers", function(err, recordset) {
      if (err) console.log(err);
      // send records as a response
      res.json(recordset);
    });
  });

  res.statusCode = 400;
  res.statusMessage = "bad request";
  // res.json({ message: "Email Missing" });
});


这是console.info(结果)

[
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the keyboard separate from the screen?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the keyboard tilt?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is it possible to find a comfortable typing postion?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Do you have a good keyboard technique?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on the keyboard clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your mouse or other pointing device suitable to the task you're using it for?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the mouse (or other pointing device) located sufficently close to you?  ',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is there support for your wrist and forearm when using the mouse(or other pointing device)',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Does the mouse (or other pointing device) work smoothly at a speed that suits you?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Can you easily adjust the software settings for speed and accuracy of the pointer?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Are the characters on your screen clear and readable?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the text size on your screen confortable to read?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the image on your screen free from flicker and jitter?',
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: "Is your screen's specification suitable for its intended use?",
[0]     state: 'Accepted'
[0]   },
[0]   {
[0]     answer: 'yes',
[0]     question: 'Is the brightness and/or contrast on your screen adjustable?',
[0]     state: 'Accepted'
[0]   }
[0] ]

错误

RequestError: Invalid length parameter passed to the LEFT or SUBSTRING function.

最佳答案

此解决方案将源行转换为 json 字符串(您的日志行已经与 json 非常相似,因此只需要进行微小的更改)。这样您就可以使用标准 SQL Server 函数来读取它们的值,从而使代码更干净、更易于维护,并且希望比我的其他建议更健壮。

仍然使用 string_split 函数和换行符来分隔行。

create procedure StoreAnswers(@text varchar(max))
as begin
  insert into QuestionResponses(question, answer, state)
  select json_value(json, '$.question') as question,
         json_value(json, '$.answer') as answer,
         json_value(json, '$.state') as state
  from (select replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ') as json
        from string_split(@source, char(10))
        where value like '%{%}%') as jsons
end;

json_value 是从 json 字符串中提取值的 SQL 函数。

从源代码行转换为 json 的示例。来自:

0: {answer: "yes", question: "Is the keyboard separate from the screen?", state: "Declined with soloution defined"}

...我们将其转换为:

{"answer": "yes", "question": "Is the keyboard separate from the screen?", "state": "Declined with soloution defined"}

我们只是删除初始行号,并在标识符中添加引号。此表达式执行这些更改:

replace(replace(replace(substring(value, charindex('{', value), len(value)), 'answer: ', '"answer": '), 'question: ', '"question": '), 'state: ', '"state": ')

在这里您可以实时看到从源文本中提取每个值:http://sqlfiddle.com/#!18/9eecb/74419

关于javascript - 将对象数组分解为单独的变量以进行数据库存储(React、express、sql server),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60277294/

相关文章:

javascript - 浏览器可能不使用缓存

javascript - jQuery:.append 或 .appendTo PHP 到 HTML 标记内的元素?

javascript - MVVM 绑定(bind)后添加到 Kendo MultiSelect

javascript - 如何让 promise 在开 Jest 中落空

mysql - 如何在 MySQL 中查询具有地理空间 "point"字段的表

mysql - 是否有一个查询只从一个表中选择列,如果仅按该表的主键分组,会给出不正确的结果?

sql-server - TVP 不符合表类型

sql - ORA-12545: 连接失败,因为目标主机或对象不存在

sql-server - 如何从 SSISDB 编写已部署的 SSIS 项目脚本 - SqlServer 2012

sql-server - 能否将delete SQL语句转换为DBT?