You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MySQL XDev API JavaScript获取全量促销码时绑定参数的问题求助

如何通过MySQL X DevAPI的LIKE条件获取所有促销码?

我来帮你排查这个问题——你遇到的情况主要是代码里的两个核心问题掩盖了LIKE参数的正确用法,导致返回undefined或无数据:

问题1:路由回调的参数顺序错误

你的router.post回调函数第一个参数写的是res,但Express路由的回调参数顺序必须是(req, res)——第一个是请求对象,第二个才是响应对象。参数顺序错了会导致你后续调用res.send()时用的根本不是正确的响应对象,这会引发各种异常。

问题2:Promise链没有传递查询结果

在第一个.then()里,你调用了promoTable.execute()但没有return这个Promise,导致下一个.then()完全拿不到查询结果,自然会得到undefined。

关于LIKE通配符的正确用法

MySQL的LIKE语法里,匹配所有内容的通配符是%:

  • '*'是错误的——MySQL不把*当作LIKE通配符
  • ' '只会匹配值为空格的促销码
  • '%%'其实和'%'效果一致,但因为上面两个问题,你根本没看到正确结果

修正后的完整代码

router.post('/getpromocodes', function(req, res){ // 修正参数顺序,添加req参数
  mysqlx.getSession(stageConnectionmysqlx)
    .then(function(session){
      var promoTable = session.getSchema('exampleTable').getTable('promo')
      // 必须return execute()返回的Promise,才能让下一个then拿到结果
      return promoTable
        .select(['promo_code', 'promo_percentage', 'expiration_date'])
        .where('promo_code like :promo_code')
        .bind('promo_code', '%') // 正确的全匹配通配符
        .execute()
    })
    .then(function(result){
      let data = result.fetchAll()
      console.log('Here is the data', data)
      res.send(data)
    })
    .catch(function(err){
      console.log('the following error occured: ' + err.message)
      res.status(500).send({ error: err.message }) // 给前端返回错误状态和信息,更友好
    })
})

额外补充:如果需要包含NULL值的记录

如果你的promo_code字段存在NULL值,且你也想获取这些记录,可以修改WHERE条件:

.where('promo_code like :promo_code OR promo_code IS NULL')

这样就能拿到所有促销码记录了。

内容的提问来源于stack exchange,提问作者nmsdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:42:35