How to use Node+MySQL+express to add, delete, modify and query

Posted by ukspudnie on Tue, 09 Jun 2020 07:08:23 +0200

First of all, thank you for this little sister's video: Bili bilibili - very poor female programmer

 

List structure attached:

1, Development preparation

  1. Node installation and configuration

  2. MySQL installation and configuration

  3. Database visualization tools: Navcat

  4. Interface test tool: Postman

  5. express

    • Installation: npm install express -g

    • NPM install - G express generator (after express 4. X, the generator is separated)

The above installation and configuration shall be solved by yourself

2, Create and initialize project

1. Create project: Express < project name >

The created directory of express apiLearn is as follows

 

2. Dependence needed

Next, vsCode opens the project to install the required dependency npm install

After the installation is successful, you can start the project: npm start

Browser access: localhost:3000 (the default port of the project is 3000, see bin/www for details)

3, Coding

The initialization of the project is completed, and then the elegant code tapping is started~

1. Overwrite the entry file

The entry file was in the bin/www directory, now we change it to app.js And delete the bin directory

Now use node app.js Start project access localhost:3000 Still accessible

2. Database installation and creation

1. Install mysql: npm install mysql --save

2. Create a database and a new table with Navcat, and add some data, which will be used later

3. Connect to database

Then there's the official code,

Create the utils folder in the change directory and create dbconfig.js To connect to the database;

const mysql = require('mysql');

// Database configuration
module.exports = {
    config: {
        host: "localhost",
        port: "3306",
        user: "root",
        password: "123456",
        database: "demo"
    },
    // Connect to database and use connection pool
    // Connection pool object
    sqlConnect: function (sql, sqlArr, callback) {
        var pool = mysql.createPool(this.config);
        pool.getConnection((err, conn) => {
            console.log("Database connection pool");
            if (err) {
                console.log("connection failed");
                return;
            } else {
                console.log("Connection successful...");
            }
            // Event driven callback
            conn.query(sql, sqlArr, callback);
            // Release connection
            conn.release();
        })
    }
}

4. Write interface

Note: for post request, the body parser plug-in needs to be installed, npm install body parser -- save, and import in the entry file

Officially enter the write interface phase

  • Create a new controller in the change directory/ students.js

Attach Code:

var dbConfig = require('../utils/dbconfig')

// check
getStudent = (req, res) => {
    var sql = "select * from students";
    var sqlArr = [];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: 'Get error!',
                'list': data
            })
        } else {
            res.send({
                code: 200,
                msg: 'success',
                'list': data
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// Check according to id
getStudentId = (req, res) => {
    let { id } = req.query;
    var sql = "select * from students where id = ?";
    var sqlArr = [id];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: 'Get error!',
            })
        } else {
            res.send({
                code: 200,
                msg: 'success',
                'list': data
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// increase
addStudent = (req, res) => {
    let { head_img, name, age, sex, intro } = req.body;
    console.log(req.body)
    var sql = "insert into students(id,head_img,name,age,sex,intro) value (?,?,?,?,?,?)";
    var sqlArr = [Math.random().toString(36).substr(-10), head_img, name, age, sex, intro];
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: 'Add failed',
            })
        } else {
            res.send({
                code: 200,
                msg: 'Successfully added',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// delete
// increase
deleteStudent = (req, res) => {
    let { id } = req.query;
    let sql = 'delete from students where id = ?'
    let sqlArr = [id]
    var callBack = (err, data) => {
        if (err) {
            res.send({
                code: 400,
                msg: 'Delete failed!!'
            })
        } else {
            res.send({
                code: 200,
                msg: 'Delete successfully!!',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
// modify
editStudent = (req, res) => {
    let { id,head_img,name,age,sex,intro } = req.body;
    let sql = 'update students set head_img=?,name=?,age=?,sex=?,intro=?where id = ?'
    let sqlArr = [head_img,name,age,sex,intro,id]
    var callBack = (err, data) => {
        if (err) {
            console.log(err)
            res.send({
                code: 400,
                msg: 'Change failed!!'
            })
        } else {
            res.send({
                code: 200,
                msg: 'Change succeeded!!',
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack);
}
module.exports = {
    getStudent,
    getStudentId,
    addStudent,
    deleteStudent,
    editStudent
}  
  • Create new routes under directory change/ students.js

Attach Code:

var express = require('express');
var router = express.Router();
const studentController = require('../controller/student')

/* GET users listing. */
//check
router.get('/all', studentController.getStudent);
//Check according to id
router.get('/byId', studentController.getStudentId);
//increase
router.post('/add', studentController.addStudent);
//Delete
router.delete('/delete', studentController.deleteStudent);
//to update
router.post('/edit', studentController.editStudent);

module.exports = router;
  • Import in entry file

Attach code

4, Testing

Here, we use postman to test the interface. We will not test how to test it.

 

Finally, it realizes the function of adding, deleting, modifying and checking~~~~~~~~

 

Topics: SQL Database MySQL npm