NodeJS 如何在SQL中为节点REST API使用带有占位符的动态where子句

nr9pn0ug  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(123)

我想构建一个SQL查询,以便可以使用占位符动态添加筛选子句。
例如:

router.get('/test',(req,res) => {
    const {name , account , id} = req.query
    const nameFilter = name === '' ? ':nameVal' : `and username = :nameVal` 
    const accountFilter = account === '' ? ':accountVal' : `and accountnumber = :accountVal`

    const result = connection.execute(' SELECT * FROM WHERE ID = :idVal ' + nameFilter + accountFilter),
      {
        nameVal : name,
        accountVal : account,
        idVal : id 
      },
    }
  res.send(result.rows)
)

现在的问题是,当查询参数有数据时,过滤器工作正常,但是当传递空字符串时,我得到一个SQL错误
非法变量名/编号
设计具有此类需求的查询的最佳解决方案是什么?
当查询参数传递有值或无值时,过滤器可以动态工作,在查询中具有占位符。

ndh0cuux

ndh0cuux1#

我不知道我是否理解了,但是当你只传递':nameVal'时,你正在做这个'SELECT * FROM TABLE WHERE ID =:idVal:nameVal',最好不要传递任何条件给查询,所以看起来像这样:

const nameFilter = name === '' ? '' : `and username = :nameVal` 
const accountFilter = account === '' ? '' : `and accountnumber = :accountVal`
qxsslcnc

qxsslcnc2#

若要处理查询参数为空字符串的情况,可以在筛选子句中使用OR逻辑运算符。
例如:

router.get("/test", (req, res) => {
  const { name, account, id } = req.query;
  const nameFilter = name === "" ? ":nameVal" : `and username = :nameVal`;
  const accountFilter =
    account === "" ? ":accountVal" : `and accountnumber = :accountVal`;

  const query =
    "SELECT * FROM table WHERE ID = :idVal " + nameFilter + accountFilter;
  const queryParams = {
    idVal: id,
    nameVal: name || null,
    accountVal: account || null,
  };

  const result = connection.execute(query, queryParams);
});

请使用上面的代码。

相关问题