首页 > 其他分享 >express实现批量删除和分页

express实现批量删除和分页

时间:2023-01-07 23:24:37浏览次数:41  
标签:code 分页 批量 res express send currentPage pageSize sqlStr

后端代码批量删除

// 批量删除
router.get('/manyDel', function (req, res) {
  let { ids } = req.query
  if (ids&&ids.length>0) { //如果用户的值为空,不执行下面的
    const sqlStr = `delete from account where id in (${ids})`
    // 打印出你的sql语句,如果报错了,可以把下面的语句放在mysql中去执行一下,目的检测sql语句是否正确
    console.log('sqlStr',sqlStr)
    connection.query(sqlStr, (err, data) => {
      if (err) {
        res.send({
          code: 1,
          msg:'批量删除失败'
        });
        throw err 
      } else {
        //这个判断是否删除成功,因为有可能没有这个id的
        if (data.affectedRows>0) {
          res.send({
            code: 0,
            msg:'批量删除成功'
          });
        } else {
          res.send({
            code: 1,
            msg:'批量删除失败'
          });
        }
      }
    })
  } else {
    res.send({
      code: 1,
      msg:'请选择'
    });
  }
})

前端批量删除代码

sendApi5() {
  axios.get('http://127.0.0.1:666/accounts/manyDel', { params: { ids: [] } }).then(function (response) {
      console.log(response);
  }).catch(function (error) {
      console.log(error);
  });
}

后端分页查询

// 分页查询
router.get('/fenye', function (req, res) {
  let { pageSize, currentPage } = req.query;
  pageSize = pageSize ? pageSize : 5;
  currentPage = currentPage ? currentPage : 1;
  let sqlStr = `select * from account order by ctime desc`;
  connection.query(sqlStr, (err, data) => {
    if (err) {
      res.send({
        code: 1,
        msg:'分页查询失败'
      });
      throw err
    } else {
      let total = data.length;
      // 分页条件
      let n = (currentPage - 1) * pageSize
      // 然后在拼接Sql语句, 逃过多少条,输出多少条,注意这里前面有一个空格,否者会报错SQL; 
      // 在Sql报错的时候,你可以看控制台的报错信息
      sqlStr += ` limit ${n}, ${pageSize}`;
      
      // 在输出条件后的Sql语句
      connection.query(sqlStr, (e, d) =>{
        if (e) {
          res.send({
            code: 1,
            msg:'分页查询失败',
            total:0
          });
          throw e
        } else {
           res.send({
            code: 0,
            data:d,
            total:total
          });
        }
      })
    }
  })
})

前端分页代码

sendApi6() {
  axios.get('http://127.0.0.1:666/accounts/fenye', {
      params: { 
          pageSize:5, currentPage:1
  } }).then(function (response) {
      console.log(response);
  }).catch(function (error) {
      console.log(error);
  });
}

我发现的问题

1. 如何高效去处判断前端是否把必须传递的参数传递过来了。
现在写的代码中,都没有去判断参数的正确性,直接进行执行了SQL语句,这样是不正确的。

2.返回体应该进行统一的封装,而不是在请求的时候像现在这样去写重复代码。

3.我现在在执行 select * from account 这样的SQL语句其实性能值非常低的,怎么去优化。

标签:code,分页,批量,res,express,send,currentPage,pageSize,sqlStr
From: https://www.cnblogs.com/IwishIcould/p/17033840.html

相关文章