1.用的是nodejs 的express框架,db.js如下:
const mysql = require("mysql")
module.exports = {
query(sql, params, callback) {
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "ceshi"
})
connection.connect(err => {
if (err) {
console.log("数据库连接失败!")
throw err
}
console.log("数据库连接成功!");
})
connection.query(sql, params, (err, results, fileds) => {
if (err) {
console.log("数据库连接失败!")
throw err
}
callback && callback(results, fileds)
})
connection.end(err => {
if (err) {
console.log("数据库关闭失败!")
throw err
}
console.log("数据库关闭成功!")
})
}
}
2.router中使用db.js
const express = require("express")
const router = express.Router();
const db = require("../config/db")
router.get("/user", (req, res, next) => {
// res.send("user")
const sql = "select * from easyuser where 1=1"
db.query(sql, [], results => {
res.json({
errno: 0, message: results
})
})
})
module.exports = router
3.app.js新增这两行
...
const useRouter = require("./router/user")
...
app.use(useRouter)
...
4.运行项目,即可查询到结果
下一篇:支持Promise