1.连接数据库配置
module.exports = {
mysql: {
host: '127.0.0.1',//本地
user: 'root', //数据库账号
password: '123456',//数据库密码
database: 'mhzqx',//数据库名
port: 3306 //数据库端口号
}
}
2. 安装mysql 插件
npm i mysql -S
3.封装连接mysql
var mysql = require('mysql')
var dbConfig = require('../db/dbConfig')
var pool = mysql.createPool(dbConfig.mysql)
module.exports = function (sql) {
return new Promise(function (resolve, reject) {
pool.getConnection(function (err, conn) {
if (err) {
reject(err);
} else {
conn.query(sql, function (err, res) {
//释放连接
conn.release();
//传递Promise回调对象
resolve({
err,
data: res
});
});
}
});
});
};
4. 使用
//引入
const express = require('express');
const router = express.Router();
let conn = require('../../db/conection')
// 根据商品id获取商品信息
router.get("/getGoodsByGid", async (req, res) => {
let {gid} = req.query
let sql = `select * from goods where GID=${gid}`
let result = await conn(sql)
if (result.data) {
res.json({
status: 200,
msg: '获取成功',
data: result.data[0]
})
} else {
res.json({
status: -1,
msg: '获取失败'
})
}
})
module.exports = router;
网友评论