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

MySQL 8.0.15 winx64 installation and configuration method graphic tutorial

This article shares the installation and configur...

How to configure two-way certificate verification on nginx proxy server

Generate a certificate chain Use the script to ge...

How to implement the paging function of MyBatis interceptor

How to implement the paging function of MyBatis i...

Analyze how to automatically generate Vue component documentation

Table of contents 1. Current situation 2. Communi...

User experience analysis of facebook dating website design

<br />Related article: Analysis of Facebook&...

Detailed explanation of how to use join to optimize SQL in MySQL

0. Prepare relevant tables for the following test...

Some tips on speeding up the development of WeChat mini-programs

1. Create a page using app.json According to our ...

Detailed explanation of HTML document types

Mine is: <!DOCTYPE html> Blog Garden: <!...

Example code for implementing transparent gradient effects with CSS

The title images on Zhihu Discovery columns are g...

Solution to the problem of English letters not wrapping in Firefox

The layout of text has some formatting requiremen...

HTML drag and drop function implementation code

Based on Vue The core idea of ​​this function is ...

iframe multi-layer nesting, unlimited nesting, highly adaptive solution

There are three pages A, B, and C. Page A contains...

Understanding MySQL precompilation in one article

1. Benefits of precompilation We have all used th...