gpt4 book ai didi

mysql - 在 mysql for nodejs 的 where 子句中使用变量与硬编码

转载 作者:行者123 更新时间:2023-11-30 22:09:10 25 4
gpt4 key购买 nike

我正在为 nodejs 使用 npm mysql 驱动程序。如何在查询的 where 子句中使用变量?

//-----这样不行,这里我是在where子句中使用变量。------

app.get('/query1', function (req, res) {    
var seat_id = req.query.seat_id

connection.query('SELECT * FROM seatpic where seatsid = "seat_id" ',function(err,rows,fields){
if(err){
console.log('There is an error in the query!');
}else {
console.log("value of var seat_id is:" ,seat_id);
console.log('Data received from Db:\n');
console.log(rows);
}

res.json (rows)

});

});


//-----This works. Hardcoding the where clause with a number.---------


app.get('/query1', function (req, res) {
var seat_id = req.query.seat_id

connection.query('SELECT * FROM seatpic where seatsid = 6 ',function(err,rows,fields){
if(err){
console.log('There is an error in the query!');
}else {
console.log("value of var seat_id is:" ,seat_id);
console.log('Data received from Db:\n');
console.log(rows);
}

res.json (rows)

});

});

最佳答案

您可以在查询中使用 ? 并将值作为数组提供,如下所示

connection.query("SELECT * FROM seatpic where seatsid = ?", [seatid], function(err,rows,fields){...

其中 [seatid] 是一个包含您的动态值的数组。

有关更多信息,请参见以下内容 - https://www.npmjs.com/package/mysql#performing-queries

关于mysql - 在 mysql for nodejs 的 where 子句中使用变量与硬编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40684447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com