2016-11-18 75 views
1

我正在爲nodejs使用npm mysql驅動程序。 如何在查詢的where子句中使用變量?使用變量與hardcoding在where子句中使用mysql for nodejs

// ------這不work.Here我使用的變量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) 

}); 

}); 

回答

0

您可以在查詢中使用?和提供值如下所示

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

其中[seatid]是一個包含您的動態值的數組。

查看以下更多 - https://www.npmjs.com/package/mysql#performing-queries

+0

謝謝!解決問題並感謝鏈接解釋。 – Donny