https://blog.csdn.net/jefferylong/article/details/118059985
把对mysql的封装,使其返回Promise。
和上篇一样,只需修改db.js
和user.js
。
1.db.js
```handlebars
const mysql = require("mysql")
module.exports = {
query(sql, params) {
return new Promise((resolve, reject) => {
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "ceshi"
})
connection.connect(err => {
if (err) {
console.log("数据库连接失败!")
reject(err)
}
console.log("数据库连接成功!");
})
connection.query(sql, params, (err, results, fileds) => {
if (err) {
console.log("数据库连接失败!")
reject(err)
}
resolve({ results, fileds })
})
connection.end(err => {
if (err) {
console.log("数据库关闭失败!")
reject(err)
}
console.log("数据库关闭成功!")
})
})
}
}
2.user.js
```javascript
const express = require("express")
const router = express.Router();
const db = require("../config/db")
router.get("/user", async (req, res, next) => {
// res.send("user")
const sql = "select * from easyuser where 1=1"
const { results } = await db.query(sql, [])
res.json({ errno: 0, message: results })
})
module.exports = router