上篇介绍了MySQL的基本的操作API,又在某篇介绍了Node.js的异步编程方式。本篇介绍如何异步操作MySQL数据库。
/**
* MySQL数据库异步操作
*/
const util = require("util");
const sql = require("mysql2");
const co = require("co");
//加载数据库驱动模块
const sqlPromise = require("mysql2/promise");
//------使用sql2/promise对象异步操作数据库----------
const pool = sqlPromise.createPool({
host:"localhost",
user:"root",
password:"wlq0MySQL@",
database:"studentdb"
});
pool.getConnection().then((conn)=>{
let res = conn.query("select * from student");
conn.release();
return res;
}).then((res)=>{
console.log("====sql2/promise数据库查询结果如下=======");
console.log(util.inspect(res[0]));
}).catch((err)=>{
console.log("连接时或查询时错误:"+err);
});
//-------------使用co模块异步操作数据库------------
co(function*(){
let conn = yield sqlPromise.createConnection({
host:"localhost",
user:"root",
password:"wlq0MySQL@",
database:"studentdb"
});
let res = yield conn.query("select * from student");
console.log("=========co模块查询结果如下========");
console.log(util.inspect(res[0]));
yield conn.end();
});
//---------------使用async/await函数异步操作数据库------------
async function getStudentInfos()
{
let pool = sqlPromise.createPool({
host:"localhost",
user:"root",
password:"wlq0MySQL@",
database:"studentdb"
});
let res = await pool.query("select * from student");
await pool.end();
return res;
}
getStudentInfos().then((res)=>{
console.log("=========async/await查询结果如下========");
console.log(util.inspect(res[0]));
}).catch((err)=>{
console.error("async/await查询错误"+err);
})
运行结果如下:
把“嵌套”异步操作,通过Promse对象、co模块或async/await函数变成“同步/串行”编写方式。本质没变,代码编写方式改变,便于理解阅读。