将对象数组分解为用于数据库存储的单独变量(React、express、sql server)

Posted

技术标签:

【中文标题】将对象数组分解为用于数据库存储的单独变量(React、express、sql server)【英文标题】:Breaking down array of objects into separate variables for database storage (React,express,sql server) 【发布时间】:2020-02-18 09:11:10 【问题描述】:

我的 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"

这包括答案、问题和状态(已回答问题的状态不是反应组件中的状态)

我想做的是将这些传递给表达,以便我可以使用 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" );
);


这是控制台信息(结果)

[
[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.

【问题讨论】:

SQL Server 的版本? 我相当确定的最新版本 【参考方案1】:

此解决方案将源代码行转换为 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: 答案:“是”,问题:“键盘是否与键盘分开? screen?", state: "Declined with Solution defined"

...我们将其转换为:

"answer": "yes", "question": "键盘是否与 screen?", "state": "Declined with Solution defined"

我们只是删除了初始行号,并在标识符中添加了引号。这个表达式做了那些改变:

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

您可以在此处实时查看从源文本中提取每个值的过程:http://sqlfiddle.com/#!18/9eecb/74419

【讨论】:

【参考方案2】:

我不能说太多关于如何用 express 编写,但你需要的是一个类似的 SQL 查询

INSERT INTO `table_name`                                           
(answer, question, created_at, updated_at)
VALUES
$sql_insert_values

sql_insert_values 将是具有逗号分隔值的字符串数组。 每个字符串将代表一个字段,并且每一列都有逗号分隔的值。

如果您在某个字段上有一些唯一键或索引,请添加 ON DUPLICATE KEY UPDATE value = VALUES(value)

如果您有任何疑问,请随时询问。

PS: 发送到 SQL 的值将采用以下格式:

["(question value in string, answer value in string, date-time, date-time)", "()", "()"]。这是一个更简单的查询示例:

INSERT INTO tbl_name (a,b,c) 
VALUES(1,2,3), (4,5,6), (7,8,9);

更多信息请参考:https://dev.mysql.com/doc/refman/8.0/en/insert.html

【讨论】:

很好,那么这将如何在存储过程中完成。对象变量数据类型是什么? 您需要稍微重新格式化您的数据。 $sql_insert_values 将是一个数组。这是一个例子 ["('这是我的问题', '这是我的答案', Time.now, Time.now") , "('这是我的第二个问题', '这是我的第二个答案', Time.now, Time.now)" ] 嘿,我已经更新了存储过程工作的问题? 抱歉 henry 我对存储过程了解不多。我只能帮你查询。 @henrypf 如果您从查询中获得帮助,您可以投票赞成我的回答。【参考方案3】:

您可以使用带有换行符的 string_split 将您的文本分成几行,然后使用 substring 在这些行中分隔您的值,使用 charindex 来标识它们的位置。

declare @text varchar(max) = 
'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"'

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(@text, char(10))

您可以在这里看到提取工作:http://sqlfiddle.com/#!18/9eecb/74353

因此,接受您的文本并将其插入表中的存储过程将是:

create procedure StoreAnswers(@text varchar(max))
as begin
  insert into QuestionResponses(answer, question, 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(@text, char(10))    
end;

【讨论】:

问题、答案和状态有时会发生巨大变化,这会影响这个吗? 啊,好吧,我想如果修改这可能就是答案。目前它正在抛出错误消息`RequestError: Invalid length parameter passing to the LEFT or SUBSTRING function.` 完全更新问题,如果您知道为什么会发生这种情况,请告诉我【参考方案4】:

我认为您必须创建一个额外的表 t_servey(id, name, ...) 并在 t_question 表中使用 servey_id 以备将来使用。

t_question(
id,
servey_id, -- link on t_servey table
answer,
question,
created_at,
updated_at
)

并添加bining变量(?)以插入到表中:

insert into t_question (servey_id, answer, question, created_at, updated_at) values (?, ?, ?, ?, ?)

【讨论】:

【参考方案5】:

为什么你不在你的 express 应用中使用 orm

喜欢续集 它将使您的生活更轻松,并消除在您的应用程序中构建 sql 语句的所有麻烦

检查它的文档 https://sequelize.org/

在你的情况下使用 sequlize

1- 在数据库中创建你的表

2- 在您的快速应用程序中为该表制作模型

3-调用model.bulkCreate(整个对象)

试试看

【讨论】:

以上是关于将对象数组分解为用于数据库存储的单独变量(React、express、sql server)的主要内容,如果未能解决你的问题,请参考以下文章

PHP:将 textarea 行分解为单独的数组元素

每日一练 | python--所有可迭代对象均可通过赋值来分解成单独的变量

javascript 对象简单介绍

java - 如何使用java将sql结果集字段存储到单独的数组变量中?

Java数组基础之高效存储数据

将 Vuex 操作分解为多个文件