【问题标题】:Nodejs Mysql null value inserted on databaseNodejs Mysql空值插入数据库
【发布时间】:2022-02-03 16:20:15
【问题描述】:
app.post('', (req, res) => {
    pool.getConnection((err, connection) => {
        if (err) throw err
        console.log('connected as id' + connection.threadID)
        const params = req.body
        var name = params.name
        var tagline = params.tagline
        var description = params.description
        var image = params.image

        connection.query('INSERT INTO beers (name, tagline, description, image) VALUES (name,tagline,description,image)',
            (err, rows) => {
                connection.release()

                if (!err) {
                    res.send('Successfully added record of name' + params.name)
                } else {
                    console.log(err)
                }
            })

        console.log(req.body)
    })
})

【问题讨论】:

  • 您的查询中没有任何参数占位符 (?),也没有向查询中添加任何参数值。你认为values (name, tagline ...) 会如何神奇地拾取你的变量?

标签: javascript mysql node.js


【解决方案1】:

正如@derpirscher 建议的那样,您应该将参数值添加到查询中。

尝试像这样更改您的代码:

    const { name, tagline, description, image } = req.body.params; 
    connection.query(
      'INSERT INTO beers (name, tagline, description, image) VALUES (?, ?, ?, ?)',
      [name, tagline, description, image],
      (err, rows) => {
        connection.release();

        if (!err) {
          res.send('Successfully added record of name' + params.name);
        } else {
          console.log(err);
        }
      }
    );

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2018-11-10
    • 2022-08-14
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多