Node.js adds, deletes, modifies and checks the actual combat record of MySQL database

Node.js adds, deletes, modifies and checks the actual combat record of MySQL database

Three steps to operate the database in the project

  1. Install a third-party module for operating the MySQL database (mysql)
  2. Connect to MySQL database via mysql module
  3. Execute SQL statements through the mysql module

Specific steps for operating the database

1: Install MySQL module and express module

The MySQL module is a third-party module hosted on npm. We can run the following command to install the MySQL third-party package, through which we can establish a connection between the node.js project and the MySQL database, and then operate the database (the following code is run in the terminal)

//Install the mysql third-party module npm i mysql
//Install the express third-party module npm i express

2: Create a server through express

// Import express
const express = require('express');
// Create the server const app = express();
// Start the server app.listen(80, () => {
    console.log('http://127.0.0.1');
})

Three: Configure the MySQL module

Before using the MySQL module to operate the MySQL database, you must first perform necessary configuration on the MySQL module. The main configuration steps are as follows:

// 1. Import mysql
const mysql = require('mysql');
// 2. Establish a connection with the MySQL database var db = mysql.createPool({
    host: '127.0.0.1', // database IP address user: 'root', // database login account password: '123456', // database login password database: 'web67' // specify which database to operate });

4: Test whether the mysql module can work properly

Call the db.query() function, specify the SQL statement to be executed, and get the execution result through the callback function

// Test whether the mysql module can run normally, find all data and display it on the page db.query('select * from one', (err, data) => {
        if (err) return console.log(err.message);
        if (data.length === 0) return console.log('There is no data in the database');
        console.log(data) //data is the data found in the database})
    });

After all the above codes are prepared, start adding, deleting, modifying and checking the data in the MySQL database:

SELECT: Query all data in one data table:

Example code:

// Get data from the database app.get('/selectuser', (req, res) => {
    // Check if the database connection is successful db.query('select * from one', (err, data) => {
        //If err is not empty, it indicates an error if (err) return console.log(err.message);
        if (data.length === 0) return console.log('Failed to obtain');
        res.send(data)
    })
});

INSERT INTO: Add data to the database:

Example code:

A post request is used here. The data requested by the client needs to be received through req.body, and the data needs to be parsed through the app.use(express.urlencoded({extended:false})) code line (see the complete code below)

// Add data to the database app.post('/insertuser', (req, res) => {
    // Receive data requested by the client const body = req.body;
    // Build SQL statement const sql = 'insert into one set?'
        //Insert the data requested by the customer into the database db.query(sql, body, (err, data) => {
        if (err) return console.log(err.message);
        if (data.affectedRows !== 1) return console.log('Add failed');
        res.send({
            status: 0,
            msg: 'Add data successfully'
        })
    })
})

UPADTE: Modify the data in the database:

Example code:

// Modify the data in the database app.post('/updateuser', (req, res) => {
    //Receive data requested by the client const body = req.body;
    //Build the modified sql statement const sql = 'update one set uname=? where id=?';
    db.query(sql, [body.uname, body.id], (err, data) => {
        if (err) return console.log(err.message);
        if (data.affectedRows !== 1) return console.log('Modification failed');
        res.send({
            status: 0,
            msg: 'Data modification successful'
        })
    })
})

DELETE: Delete data in the database:

Example code:

// Delete data in the database app.get('/deleteuser/:id', (req, res) => {
    // Get the data submitted by the client, req.params matches the dynamic parameter through the colon: const id = req.params.id;
    // Build the SQL statement for deletion. Generally, in order to prevent data from being permanently deleted, we will modify the status code corresponding to the data to 0 through update
    const sql = 'update one set status=0 where id=?';
    // Execute sql
    db.query(sql, id, (err, data) => {
        if (err) return console.log(err.message);
        if (data.affectedRows !== 1) return console.log('deletion failed');
        res.send({
            status: 0,
            msg: 'Deleted successfully'
        })
    })
})

At this point, the addition, deletion, modification and query of the MySQL database are completed through the express middleware. The complete code is as follows:

// Use express middleware to add, delete, modify and check the MySQL database const express = require('express');
// Create a server const app = express();
// Parse the data requested by the client app.use(express.urlencoded({ extended: false }));
//Introduce mysql operation database const mysql = require('mysql');
// Configure the database const db = mysql.createPool({
    host: '127.0.0.1', //database ip address user: 'root', //database account password: '123456', //database password database: 'web67' //database name });
 
// Get data from the database app.get('/selectuser', (req, res) => {
    // Check if the database connection is successful db.query('select * from one', (err, data) => {
        if (err) return console.log(err.message);
        if (data.length === 0) return console.log('Failed to obtain');
        res.send(data)
    })
});
 
// Add data to the database app.post('/insertuser', (req, res) => {
    // Receive data requested by the client const body = req.body;
    // Build SQL statement const sql = 'insert into one set?'
        //Insert the data requested by the customer into the database db.query(sql, body, (err, data) => {
        if (err) return console.log(err.message);
        if (data.affectedRows !== 1) return console.log('Add failed');
        res.send({
            status: 0,
            msg: 'Add data successfully'
        })
    })
})
 
// Modify the data in the database app.post('/updateuser', (req, res) => {
    const body = req.body;
    const sql = 'update one set uname=? where id=?';
    db.query(sql, [body.uname, body.id], (err, data) => {
        if (err) return console.log(err.message);
        if (data.affectedRows !== 1) return console.log('Modification failed');
        res.send({
            status: 0,
            msg: 'Data modification successful'
        })
    })
})
 
// Delete data in the database (specify id)
app.get('/deleteuser/:id', (req, res) => {
        const id = req.params.id; //id is a dynamic parameter, so it must be obtained through req.params const sql = 'update one set status=0 where id=?'
        db.query(sql, id, (err, data) => {
            if (err) return console.log(err.message);
            if (data.affectedRows !== 1) return console.log('Failed to delete data');
            res.send({
                status: 0,
                msg: 'Deleted successfully'
            })
        })
    })
    // Start the server app.listen(80, () => {
    console.log('http://127.0.0.1');
})

Summarize

This is the end of this article about Node.js adding, deleting, modifying and querying MySQL database. For more information about Node.js adding, deleting, modifying and querying MySQL, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Analysis of mysql add, delete, modify and query operations and async, await processing examples in node.js
  • Node.js+Express+Mysql to implement add, delete, modify and query
  • An example of nodejs operating mysql to achieve addition, deletion, modification and query
  • NodeJs connects to Mysql to perform simple operations of adding, deleting, modifying and checking
  • Node.js operates mysql database to add, delete, modify and query
  • Node.js operation mysql (add, delete, modify and query)
  • Node connects to MySQL and encapsulates its implementation code for adding, deleting, modifying and checking

<<:  How to use the VS2022 remote debugging tool

>>:  CSS to achieve the transition animation effect of the picture when the mouse is placed on it

Recommend

What does input type mean and how to limit input

Common methods for limiting input 1. To cancel the...

An article to help you understand the basics of VUE

Table of contents What is VUE Core plugins in Vue...

TypeScript installation and use and basic data types

The first step is to install TypeScript globally ...

How to test the maximum number of TCP connections in Linux

Preface There is a misunderstanding about the max...

Summary of basic operations for MySQL beginners

Library Operations Query 1.SHOW DATABASE; ----Que...

Concat() of combined fields in MySQL

Table of contents 1. Introduction 2. Main text 2....

Let's learn about JavaScript object-oriented

Table of contents JavaScript prototype chain Obje...

CSS3 radar scan map sample code

Use CSS3 to achieve cool radar scanning pictures:...

Dynamically add tables in HTML_PowerNode Java Academy

Without further ado, I will post the code for you...

Mysql accidental deletion of data solution and kill statement principle

mysql accidentally deleted data Using the delete ...

A brief discussion on the synchronization solution between MySQL and redis cache

Table of contents 1. Solution 1 (UDF) Demo Case 2...