简体   繁体   English

使用 Express 和 MySQL 模块通过 NodeJS 更新记录时出现 SQL 语法错误

[英]SQL syntax error when updating record via NodeJS with Express and MySQL modules

I'm getting an "app crashed" error in Visual Studio Code's terminal when I try to update a MySQL record in NodeJS.当我尝试在 NodeJS 中更新 MySQL 记录时,我在 Visual Studio Code 的终端中收到“应用程序崩溃”错误。

app2.js: 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: 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>

The error in Powershell: 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...

Query that works in MySQL Console: You can see it works.在 MySQL 控制台中有效的查询:您可以看到它有效。

Using WAMP server (because I'm rebuilding a previous Visual Basic WinForms app as a web app): MySQL: 5.7.9 Apache: 2.4.17使用 WAMP 服务器(因为我正在将以前的 Visual Basic WinForms 应用程序重建为 Web 应用程序): MySQL:5.7.9 Apache:2.4.17

I swear the above worked just a few days ago, but the environment may have changed a little in that time (eg installing more node modules, that kind of thing, though I was definitely using the WAMP server at the time).我发誓以上几天前才奏效,但当时环境可能已经发生了一些变化(例如,安装更多节点模块之类的事情,尽管我当时肯定在使用 WAMP 服务器)。

Any help appreciated.任何帮助表示赞赏。

Edit: I'm experiencing no problem selecting from or inserting into the MySQL database using NodeJS.编辑:我在使用 NodeJS 选择或插入 MySQL 数据库时没有遇到任何问题。

ADDED (after John Michael Manlupig's suggestion initially worked, at least in the original context): The problem persists in another spot.添加(在 John Michael Manlupig 的建议最初奏效之后,至少在原始上下文中):问题在另一个地方仍然存在。 I'm posting info (as "result") to app.js via a tinymce rich-text editor, but it fails out the same way when using the code below:我通过 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');     }) });

I can send the received value of "req.body.content" to the console, and it's good, but sending it through the rest of the code causes "app crashed" in the same way as described above, despite parametizing as suggested by @John Michael Manlupig, and despite the query text containing correct/expected info, and being useable as-is in MySQL Console.我可以将接收到的“req.body.content”值发送到控制台,这很好,但是通过其余代码发送它会导致“应用程序崩溃”以与上述相同的方式,尽管按照@的建议进行了参数设置John Michael Manlupig,尽管查询文本包含正确/预期的信息,并且可以在 MySQL 控制台中按原样使用。

Anything obvious I'm overlooking?有什么明显的我忽略了吗?

You should parametize the values instead of inserting it directly into the string.您应该对值进行参数化,而不是将其直接插入到字符串中。

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');
});

I think I've identified the ghost in the machine.我想我已经确定了机器中的幽灵。 I recently started saving useful blocks of code in OneNote, and was then recently copying-n-pasting from OneNote into Visual Studio Code.我最近开始在 OneNote 中保存有用的代码块,然后最近从 OneNote 复制粘贴到 Visual Studio Code。 Visual Studio wasn't telling me anything was wrong, and lots of it worked, but it looks strongly like there was invisible junk in there (at least some of the time). Visual Studio 没有告诉我有什么问题,而且很多都有效,但看起来很像那里有看不见的垃圾(至少在某些时候)。 Ugh!啊!

Thanks for all the help, as it was a necessary part of the solution!感谢所有帮助,因为它是解决方案的必要部分!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM