【问题标题】:inserting multiple records in mySQL data base from react-native and node-js从 react-native 和 node-js 在 mySQL 数据库中插入多条记录
【发布时间】:2021-01-06 19:16:17
【问题描述】:

我有一个发票应用程序,您可以在其中将许多产品添加到同一张发票(账单)中 在 mySQL 中,我有一个产品表,我想在其中添加我在发票中添加的每个产品。 我已经设法将所有产品保存在一个数组中。

Array [
  Object {
    "amt": "1",
    "desc": "Item1",
    "index": 0,
    "qty": "1",
  },
  Object {
    "amt": "2",
    "desc": "Item2",
    "index": 1,
    "qty": "2",
  },
  Object {
    "amt": "3",
    "desc": "Item3",
    "index": 2,
    "qty": "3",
  },
  Object {
    "amt": "4",
    "desc": "Item4",
    "index": 3,
    "qty": "4",
  },
]

单击按钮时,我想发送一个 api,将数据插入到 mySQL 中的表中。

 app.post("/addproducts", (req, res) => {
      let product= req.body;
      var sql =
        "INSERT INTO products (amt, desc, qty, invoiceId) VALUES(?, ?, ?, ?);";
      mysqlConnection.query(
        sql,
        [
          product.invoiceId,
          product.amt,
          product.desc,
          product.qty,
        ],
        (err, rows, fields) => {
          if (!err) {
            res.send(rows);
            });
          } else {
            res.send(err);
          }
        }
      );
    });

如何修复我的 api 以逐个遍历数组并将所有产品插入表中

PS:invoice id 是产品表中的外键(不要介意)

axios
      .post("http://192.168.0.117:3000/addInvoice", {
        address: address,
        invoiceId: invoiceId,
        amt: invoicenumber,
        desc: desc,
        qty: qty,
      })
      .then((response) => {
        alert("Invoice sent to customer!");
      })
      .catch((error) => console.log("error", error));
  };

这是前端的post api

如何映射数据数组(我在开头显示的)并逐个发送对象?

【问题讨论】:

  • 嗯,某种循环似乎是一个可能的起点

标签: mysql node.js reactjs react-native


【解决方案1】:

使用嵌套数组可以进行批量插入。

在您的情况下,数据应如下所示:

var sql =
    "INSERT INTO products (amt, desc, qty, invoiceId) VALUES(?, ?, ?, ?);";

let values = [
  ['1', 'Item1', '0', '1'],
  ['2', 'Item2', '1', '2'],
  ...
]

mysqlConnection.query(sql, values, ...)

(关心字段顺序)

【讨论】:

  • 是的,但是我如何将数据从前端发送到后端
  • 你能帮我吗?
  • 此编辑添加了另一个不相关的问题,您应该将其添加到另一个线程中,因为它与向 MySQL 插入多条记录没有任何关系
猜你喜欢
  • 1970-01-01
  • 2020-03-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多