我正在尝试根据用户选择的表将数据从表发送到客户端。
/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM ?',
[req.params.id],
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//END SERVE
从上面开始,我期待表中的所有数据,但是当我执行诸如“ localhost:1234 / data / alert”之类的操作时,我不断收到下面的错误
{
"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 ''alert'' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "SELECT * FROM 'alert'"
}
由此,我确实意识到错误是因为表名被引用了;如何解决此错误?
答案 0 :(得分:0)
有两种方法-
/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM '+ req.params.id,
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//END SERVE
编辑-如@RiggsFolly的注释中所述,查询串联可能导致Sql注入攻击。请记住这一点。
mysql
模块,请使用内置方法/** GET ALL VAULES IN A PARTICULAR TABLE */
serve.get('/data/:id', (req, res)=>{
dbConn.query(
'SELECT * FROM ??',
[req.params.id],
(error, rows)=>{
if(!error){
//when there is no error
res.send(rows);
}else{
//when there is an error
res.send(error);
}
});//END dbConn
});//
?
用于值,??
用于转义查询标识符。