Use Egg to call mysql to realize the interface operation of adding, deleting, modifying and checking

There are many database visualization tools on the market. I use Navicat more often, but because it is charged, some partners may not use it, so I recommend a tool called DBevaer here. The capabilities it demonstrates, Similar to navicat, and it is also free and open source. In this chapter, partners will download DBevaer by themselves and work with the author. Due to different tools, some places may not be correct for the author. So everyone here is a reference for the visualization tool.

Download link: Download | DBeaver Community

Link to local database

In the last chapter, the author has connected to the database at the end. What needs to be explained here is that if your database has not modified the port, then the default database port must be 3306, so you can open the software after downloading the tool, and then create a new connection and enter the host name (in the last lesson we The default is localhost), port number (default 3306), and user name (root), password (set in the previous lesson)

Click OK after modification.

We double-click again to link to the local server. If there is an error here, it may be because mysql is not enabled. Under the window, you can use cd to the bin directory of the mysql decompression directory, and use the command line: net start mysql to start the local mysql

Then we can select the corresponding database in the current local library.

At this time, our visualization tool is officially connected to mysql.

Next, we can successfully connect our Egg project by creating a new database. And do some simple operations.

Egg link Mysql

First, we create a new database for subsequent operation demonstration.

 

Create a new test database as follows:

 

Then we create a new data table in the current tset database

 

The name of the table is list, and there is a field id in the table, which is of int type. We set it to be non-nullable and self-incrementing, and set its primary key

 

Then add a new field name, the type is varchar.

Finally, save and refresh the table, and assign values ​​to its two fields by default, 0 and Nick

 

Egg connects to the database to implement the query interface

After completing the basic data of the database, we open the previous project. Install plugin egg-mysql

npm install egg-mysql

After the installation is complete, open the directory config/plugin.js to add the plugin configuration

module.exports = {
    ejs:{
        ...
    },
        mysql:{
            enable: true,
            package: 'egg-mysql'
        }
}

Then configure config/config.default.js to initialize the configuration

 config.mysql = {
    // 单数据库信息配置
    client: {
      // host
      host: 'localhost',
      // 端口号
      port: '3306',
      // 用户名
      user: 'root',
      // 密码
      password: '294857697182', // 初始化密码,没设置的可以不写
      // 数据库名
      database: 'test', // 我们新建的数据库名称
    },
    // 是否加载到 app 上,默认开启
    app: true,
    // 是否加载到 agent 上,默认关闭
    agent: false,
  };

Next, we need to modify service/home.js to get the database

const Service = require('egg').Service;
class HomeService extends Service {
  async user() {
    const { ctx, app } = this;
    const QUERY_STR = 'id, name';
    let sql = `select ${QUERY_STR} from list`; // 获取 id 的 sql 语句
    try {
      const result = await app.mysql.query(sql); // mysql 实例已经挂载到 app 对象下,可以通过 app.mysql 获取到。
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}
module.exports = HomeService;

Finally, modify the controller and router.

// controller/home.js
async user () {
    const {ctx} = this;
    const result = await ctx.service.user();
    ctx.body = result
}
// app/router.js
router.get('/user', controller.home.user);

After all modifications, we start the project and open http://127.0.0.1:7001/user to access the current user interface.

 

The corresponding data in the database has been queried on the page.

We can also add another piece of data in the database and refresh the next page to view it.

 

The value queried on the page will also change accordingly.

 

So the principle of the database is the same as what I said at the beginning. It is a thing that stores data, and when we contact the background, we must not get around the database. After all, the interface party writes the interface to call or process data.

We get the id and name field values ​​of the list table by calling the /user interface of get, and return them in an array.

Egg implements the new interface

The query interface has been implemented above, and we will add a new interface. First, create a new service processing method named addUser in service/home.js


async addUser (name) {
    const { ctx,app } = this;
    try {
        const result = await app.mysql.insert('list', { name }); // 给list表新增一条数据
       return result;
    }catch(error) {
        console.log(error);
        return null;
    }
}

After modifying the service, we need to add the corresponding addUser method to the controller that responds to the request.

async addUser () {
    const {ctx} = this;
    const {name} = ctx.request.body;
    try {
        const result = await ctx.service.addUser(name);
        ctx.body = 
            code: 200,
            mag: '添加成功',
            data: null
    }catch (error) {
        ctx.body = {
           code: 500,
            msg: '添加失败',
            data: null
        }
    }
}

Again, after we're done, we throw the router.

// app/router.js
router.post('/add_user', controller.home.aduser)

Enable postman for data interface requests

 

Return to add successfully, and then look at the data table.

 

has also been inserted.

When we request the /user interface again, there will be three pieces of data on the page

edit interface

Before writing the editing interface, students can imagine what it was like when they called the background interface before, that's right. It is necessary to pass the primary key and the modified data, and we need to determine which value of a certain field is modified.

So the editing interface definitely needs at least two fields, one is id to find which value it is. name is the latest value that needs to be edited.

Let's try to write

First of all, write service first

//service/home.js
async editUser (id, name) {
    const { ctx, app } = this;
    try {
        const result = await app.mysql.update('list', { name }, {
            where: {
                id
            }
        });
        return result
    }catch (error) {
        console.log(error)
        return null;
    }
}

// Next write the controller

// controller/homs.js
async editUser () {
    const { ctx } = this;
    const { id, name } = ctx.request.body;
    try{ 
        const result = await ctx.service.home.editUser(id, name);
        ctx.body = {
            code: 200,
            msg: '修改成功',
            data: null
        }
    }catch(error) {
       ctx.body = {
           code: 500,
           msg: '修改失败',
           data: null
       }
    }
}

In the end, add the router in the same way

router.put('/edit_user', app.controller.home.editUser);

After following the above, we can open postman again to make calls. Below is the old data

 

I am modifying after calling postman

 

Then call the /user query interface to query the latest data.

 

The modification has been completed.

delete interface

In fact, the deletion interface has been done well with the above query, addition and modification.

In order to facilitate the distinction, we use the delete request to delete the interface.

service is as follows

async delUser () {
    const { app } = this;
    try {
        const result = app.mysql.delete('list', {
            id,
        })
    }catch (error) {
        return null;
    }
}

The controller is as follows:

async delUser() {
    const { ctx } = this;
    const { id } ctx.query;
    try {
        const result = ctx.service.home.delUser(id);
        ctx.body = {
            code: 200,
            msg: '成功',
            data: true
        }
    }catch(error){
        ctx.body = {
            code: 500,
            msg: '失败',
            data: false
        }
    }
}

Finally, don't forget the router

router.delete('/del_user', Controller.home.delUser);

The data on the page will naturally change accordingly.

Guess you like

Origin blog.csdn.net/qq_31281245/article/details/127910114