簡體   English   中英

使用 Express 和 MySQL 模塊通過 NodeJS 更新記錄時出現 SQL 語法錯誤

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

當我嘗試在 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 控制台中有效的查詢:您可以看到它有效。

使用 WAMP 服務器(因為我正在將以前的 Visual Basic WinForms 應用程序重建為 Web 應用程序): MySQL:5.7.9 Apache: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 控制台中按原樣使用。

有什么明顯的我忽略了嗎?

您應該對值進行參數化,而不是將其直接插入到字符串中。

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

我想我已經確定了機器中的幽靈。 我最近開始在 OneNote 中保存有用的代碼塊,然后最近從 OneNote 復制粘貼到 Visual Studio Code。 Visual Studio 沒有告訴我有什么問題,而且很多都有效,但看起來很像那里有看不見的垃圾(至少在某些時候)。 啊!

感謝所有幫助,因為它是解決方案的必要部分!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM