下载mysql2依赖包
npm i mysql2
创建mysql连接实例并暴露出去
const mysql = require('mysql2')const mysqlMode = mysql.createPool({host: '127.0.0.1', //服务端hostuser: 'root', //用户名称,mysql一般默认rootpassword: '123456', //密码database: 'sqlTest1', //数据库名字waitForConnections: true, //超过最大连接数是否等待connectionLimit: 10, //最大连接个数queueLimit: 2 //等待队列最大限制
})module.exports = mysqlMode
接收请求并返回数据库的值
var express = require('express');
var router = express.Router();
const mysqlMode = require('../db/mysql')/* GET home page. */
router.get('/', function (req, res, next) {mysqlMode.query("SELECT * FROM `test01`", (error, results, fields) => {if (error) {console.error(error)return}// console.log(results)res.send(results)})
});module.exports = router;
连接成功!