当前位置:网站首页>Node connects to MySQL database and writes fuzzy query interface

Node connects to MySQL database and writes fuzzy query interface

2022-06-11 11:30:00 Yanyan is very WOW!

One 、 preparation

1. install mysql

install MySQL

2.node Install database in

// node Install in mysql
npm install mysql

3.node Connect to database

(1) stay db New file in directory sql.js

// sql.js
var mysql = require('mysql') // introduce 

var connection = mysql.createConnection({
    
    host: 'localhost', // Host name 
    user: 'root', // account number 
    password: 'root', // password 
    database: 'mysql', // The name of the library to be connected 
})

module.exports = connection

(2) stay MySQL Create tables in the database
 Insert picture description here

Two 、 Write the interface

//  stay routes Under folder index.js Write the following interfaces in 
var express = require('express')
var router = express.Router()
var connection = require('../db/sql.js')  // Bring in the connected database 

router.get('/api/goods/search', function (req, res, next) {
      // Interface 
    let [goodsName, orderName] = Object.keys(req.query)      // Parameters obtained from the front end 
    console.log(goodsName, orderName)

    let name = req.query.name

    let order = req.query[orderName]

    connection.query(
        "select * from goods_search where name like '%" +   
        // Here is the fuzzy query , By name or discount perhaps oprice Fuzzy query 
            name +
            "%' order by " +
            orderName +
            ' ' +
            order +
            '',
        function (error, result, fields) {
    
            // if (error) throw error
            res.send({
    
                code: '0',
                data: result,
            })
        }
    )
})

module.exports = router

3、 ... and 、 The test results

// By name “ Big ” and discount Field fuzzy query , among asc In ascending order ,desc For the descending order
 Insert picture description here
// By name “ Small ” and discount Field fuzzy query
 Insert picture description here

原网站

版权声明
本文为[Yanyan is very WOW!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111110362279.html