【问题标题】:SQL syntax error when updating record via NodeJS with Express and MySQL modules使用 Express 和 MySQL 模块通过 NodeJS 更新记录时出现 SQL 语法错误
【发布时间】:2021-09-26 14:22:04
【问题描述】:

当我尝试在 NodeJS 中更新 MySQL 记录时,我在 Visual Studio Code 的终端中收到“应用程序崩溃”错误。

app2.js:

const express = require('express');
const mysql = require('mysql');

// create connection
const db = mysql.createConnection({
    host: 'localhost', 
    user: 'root',
    password: '',
    database: 'journey_test'
})

 // connect to mysql
 db.connect(err => {
     if(err) {
         throw err
     }
     console.log('MySQL Connected');
 })

 const app = express()

 app.use(express.static('public'));
 app.set('view engine', 'ejs');

// this pulls index.ejs to the root folder location of the site
app.get('/', function (req, res) {
    res.render('index2');
});

app.post('/change/:artist/:id', (req, res) => {

        let newArtist = req.params.artist;
        let newID = req.params.id ;
    // even hard-setting variables in my query causes failure
     let sql = `UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'`
        let query = db.query(sql, err => {
            if(err) {
                throw err
            }
            res.send('Entry updated');
        })
    })


 app.listen('3000', () => {
     console.log('Server Started on port 3000')
 })

index2.ejs:

<!DOCTYPE html>
<html>
<head>
        <script>
           function testing() {
              var xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
              const text = this.responseText;
              const obj = JSON.parse(text);          
                     document.getElementById("Hello2").innerHTML = "Yes!";
         };
              xhttp.open("POST", "change/The Cure/104", true);
              xhttp.send();
         }
         </script>
    </head>
    <body>
        
        <button style= "height:22px";" type="button" onclick="testing()">Update</button> 
        <div id="Hello2">Did I do it?</div>
             
    </body>
</html>

Powershell 中的错误:

PS C:\Users\Mervius\Documents\NodeJS> nodemon app2.js
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app2.js`
Server Started on port 3000
MySQL Connected
C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'' at line 1
    at Query.Sequence._packetToError (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
    at Query.ErrorPacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
    at Protocol._parsePacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:433:10) 
    at Parser.write (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:38:16)     
    at Socket.<anonymous> (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:88:28)        
    at Socket.<anonymous> (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:526:10)       
    at Socket.emit (events.js:375:28)
    at addChunk (internal/streams/readable.js:290:12)
    --------------------
    at Protocol._enqueue (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\protocol\Protocol.js:144:48) 
    at Connection.query (C:\Users\Mervius\Documents\NodeJS\node_modules\mysql\lib\Connection.js:198:25)
    at C:\Users\Mervius\Documents\NodeJS\app2.js:36:24
    at Layer.handle [as handle_request] (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\route.js:112:3)        
    at Layer.handle [as handle_request] (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:281:22
    at param (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:354:14)
    at param (C:\Users\Mervius\Documents\NodeJS\node_modules\express\lib\router\index.js:365:14) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "UPDATE tblbillboardcomplete SET artist = 'The Cure' WHERE id = '104'"
}
[nodemon] app crashed - waiting for file changes before starting...

在 MySQL 控制台中工作的查询: You can see it works.

使用 WAMP 服务器(因为我将以前的 Visual Basic WinForms 应用程序重新构建为 Web 应用程序): MySQL:5.7.9 阿帕奇:2.4.17

我发誓上述方法几天前才有效,但当时环境可能发生了一些变化(例如安装更多节点模块,诸如此类,尽管当时我肯定使用的是 WAMP 服务器)。

任何帮助表示赞赏。

编辑:我在使用 NodeJS 选择或插入 MySQL 数据库时没有遇到任何问题。

添加(在 John Michael Manlupig 的建议最初奏效之后,至少在原始上下文中): 问题在另一个地方仍然存在。我通过 tinymce 富文本编辑器将信息(作为“结果”)发布到 app.js,但在使用以下代码时以同样的方式失败:

const express = require('express');
const mysql = require('mysql');
//const dayjs = require('dayjs');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/result', upload.none(), function (req, res, next) { // when we save RTE info in tinymce
    var newEntry = req.body.content
    var newDate = activedate
    const sql = `UPDATE main SET entry = ? WHERE dateID = ?`;
    const query = db.query(sql, [newEntry, newDate], err => {
        if(err) {
            throw err
        }
        res.send('Entry updated');
        })
    });

我可以将接收到的“req.body.content”值发送到控制台,这很好,但是通过其余代码发送它会导致“应用程序崩溃”的方式与上述相同,尽管参数化为由@John Michael Manlupig 建议,尽管查询文本包含正确/预期的信息,并且可以在 MySQL 控制台中按原样使用。

有什么明显的我忽略了吗?

【问题讨论】:

    标签: javascript mysql node.js express


    【解决方案1】:

    您应该对值进行参数化,而不是将其直接插入到字符串中。

    const sql = `UPDATE tblbillboardcomplete SET artist = ? WHERE id = ?`;
    const query = db.query(sql, ['The Cure', 104], err => {
        if(err) {
            throw err
        }
        res.send('Entry updated');
    });
    

    【讨论】:

    • 你成功了,约翰·迈克尔·曼卢皮格!非常感谢!
    • 更新了我原来的问题,因为建议的参数化似乎没有第二次起作用??
    【解决方案2】:

    我想我已经确定了机器中的幽灵。我最近开始在 OneNote 中保存有用的代码块,然后最近将 OneNote 中的复制粘贴到 Visual Studio Code 中。 Visual Studio 并没有告诉我有什么问题,而且很多都有效,但看起来很像那里有看不见的垃圾(至少在某些时候)。啊!

    感谢所有帮助,因为这是解决方案的必要部分!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多