nodejs通过 mysql 插件来操作mysql数据库。 使用步骤:
- 在nodejs项目中安装mysql
npm install mysql - 创建连接对象
const mysql = require("mysql");
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "chenke123",
port: "3306",
database: "myblog",
});
- 开始连接
con.connect() - 实现统一执行sql函数exec,导出exec函数
function exec(sql) {
// con.query 是异步的,封装在Promise里合适
return new Promise((resolve, reject) => {
con.query(sql, (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
}
module.exports = {
exec,
};
- 在controller层调用exec方法。比如获取详情接口getDetail
const getDetail = (id) => {
const sql = `select * from users where id='${id}'`;
return exec(sql).then((rows) => {
return rows[0];
});
};
- 在router层调用getDetail方法。
if (method === "GET" && req.path === "/api/user/detail") {
const result = getDetail(id);
return result.then((data) => {
return {data}
});
}
7.在app.js文件中集中对router层的数据做处理
const result = handleRouter(req, res);
if (result) {
result.then((data) => {
res.end(JSON.stringify(data));
});
}
express 和 koa2中,连接mysql的方式与此相同。