Node.js使用连接池连接MySQL

首先引入mysql模块

const mysql = require('mysql');

然后写连接池

const pool = mysql.createPool({
	host : 'ip',//主机地址
	user : 'root',//用户名
	password : '123456',//密码
	port : 3306,//端口
	database : 'Test'//数据库
});

最后写接口

app.get('/test',(req,res,next)=>{
	try{
		pool.getConnection(function(err,conn){
			conn.query("select * from 表",(err,r)=>{//查询语句
				if(err) console.log('[Select Error]:'+err.message);//抛错
				res.json({code:1,data:r})//返回给前端数据
			})
			conn.release();//释放连接池
		})
	}catch(err){
		return next(err);
	}
})
发布了69 篇原创文章 · 获赞 20 · 访问量 9773

猜你喜欢

转载自blog.csdn.net/qq_41980461/article/details/104016290