# primer数据表的增删改查

* 进行SQL查询的语句封装在`module/primerData.js`模块中
* 对不同路由，映射到不同的方法上

## 模块封装的方法

1. `checkInsertData`检测用户输入的数据是否合法
2. `deleteByOne`根据主键进行删除
3. `updateByOne`根据用户提交数据进行更新
4. `insertItem`根据用户数据进行插入
5. `searchByKeyword`根据关键字进行模糊搜索

### 1.首页模糊查询

```bash
router.post("/",function(req,rep,next){
  keyword=req.body.keyword;
  primerDataMethods.searchByKeyword(keyword,function(err,result){
    if(err){
      next(err)
      return
    }
    rep.send(result)
  })
})
```

### 2.新数据插入

* 调用权限验证函数进行权限的验证
* 满足权限后，对用户提交的表单数据进行验证
* 根据回调函数，返回不同的错误代码
* 前端根据错误代码，给用户不同的提示

```bash
/* 数据插入 */
router.post("/insert",function(req,rep,next){
  authenticateMethods.isLogin(req,function(err,result){
    if(err){
      next(err)
      return
    }
    if(result==0){ //cookie修改之后resule为空也需要重新登录
      rep.redirect("/login")
      return
    }
    if(primerDataMethods.checkInsertData(req.body)){
      primerDataMethods.insertItem(primerDataMethods.checkInsertData(req.body),function(err,result){
        if(err && err.sqlState=="23000"){
          rep.send(err.sqlMessage) //mysql自带错误,由于重复插入；不需要跳转到错误中间件
          return
        }else if(err){
          next(errorCategory.mysql.sql)
          return
        }
        rep.send("插入成功")
      })
    }else{
      next(errorCategory.mysql.requireFields)
      return
    }
  })
})
```

### 3.数据更新

* 检查权限
* 检测用户提交的数据

### 4.数据删除

* 检查权限
* 之间调用SQL语句进行删除
*

### 参考

1. url解析  <https://www.npmjs.com/package/url>&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zpliu.gitbook.io/booknote/qian-duan-cao-zuo/shi-li-lian-xi/dong-tai-sou-suo-wang-ye/hou-duan/07-shu-ju-de-zeng-shan-gai-cha.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
