【问题标题】:show data after inserted using sequelize raw queries in express使用 sequelize 原始查询在 express 中插入后显示数据
【发布时间】:2021-07-28 22:07:47
【问题描述】:

我正在尝试使用 sequelize 发送带有原始查询的插入数据,然后显示它。以下是我的代码:

const c_product_post = async (req, res) => {
try {
    const sql = `INSERT INTO products (p_name, p_price, p_stock, p_review, "createdAt", "updatedAt")
    VALUES ('${req.body.product_name}', ${req.body.product_price}, ${req.body.product_stock}, ${req.body.product_review}, now(), now());`
    const postData = await Product.sequelize.query(sql)
    // await postData.save()
    res.send({
        message: "success add new product",
        data: postData
    })
}
catch (err) {
    res.send({
        message: err
    })
  }
}

我想要实现的是,插入数据后会显示(见下图红色):

【问题讨论】:

    标签: node.js postgresql express sequelize.js


    【解决方案1】:

    RETURNING 子句添加到您的查询中。试试这个

    INSERT INTO products (p_name, p_price, p_stock, p_review, "createdAt", "updatedAt")
        VALUES ('${req.body.product_name}', ${req.body.product_price}, ${req.body.product_stock}, ${req.body.product_review}, now(), now()) 
    RETURNING *;
    

    请注意,您的方法非常容易使用 SQLi。考虑使用准备好的语句而不是文本替换。

    【讨论】:

    • 感谢@Stefanov.sm,它起作用了,但是很抱歉,您能否详细解释一下“考虑使用准备好的语句而不是文本替换”。我没有明白你的意思,或者如果你不介意,你可以给我一个更好的方法来处理我的查询。我还是新手,真的很抱歉有额外的问题。
    • 您可以开始深入研究herehere 的问题
    • 感谢@Stefanov.sm 我将深入研究您提供的两个链接,感谢您的帮助。
    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    相关资源
    最近更新 更多