Node连接MySql数据库写模糊查询接口
一、准备工作
1.安装mysql
2.node中安装数据库
// node中安装mysql npm install mysql
3.node中连接数据库
(1)在db目录下新建文件sql.js
// sql.js
var mysql = require(mysql) //引入
var connection = mysql.createConnection({
host: localhost, //主机名
user: root, //账号
password: root, //密码
database: mysql, //需要连接的库名
})
module.exports = connection
(2)在MySQL数据库中建立表
二、写接口
// 在routes文件夹下的index.js中写以下接口
var express = require(express)
var router = express.Router()
var connection = require(../db/sql.js) //将连接的数据库引入进来
router.get(/api/goods/search, function (req, res, next) {
//接口
let [goodsName, orderName] = Object.keys(req.query) //从前端获取过来的参数
console.log(goodsName, orderName)
let name = req.query.name
let order = req.query[orderName]
connection.query(
"select * from goods_search where name like %" +
//这里是模糊查询,根据名字或者discount或者oprice进行模糊查询
name +
"% order by " +
orderName +
+
order +
,
function (error, result, fields) {
// if (error) throw error
res.send({
code: 0,
data: result,
})
}
)
})
module.exports = router
三、测试效果
//根据名字“大”和discount字段进行模糊查询,其中asc为升序,desc为降序 //根据名字“小”和discount字段进行模糊查询
