node是基於異步的,所以在進行數據庫查詢操做的一般是經過回調來操做查詢結果。可是在有了es7的async/await,基本再也不須要回調了,因此本篇是基於async/await對mysql進行一次操做封裝,讓查詢更加方便。(node版本需>=7.0)。 node
簡單來講,async/await的實現原理是基於promise,根據promise的狀態來判斷是否真正返回,所以咱們能夠在mysql真正查詢到結果後將promise狀態切換爲resolve,返回結果。如出現錯誤經過reject返回錯誤信息,reject須要用try/catch進行捕獲。mysql
'use strict'; const mysql = require('mysql'); var local = true var pool // 建立鏈接池 if (local) { pool = mysql.createPool({ connectionLimit: 50, host: 'localhost', user: 'root', password: 'root', database: 'crawl', multipleStatements: true //是否容許執行多條sql語句 }); } //將結果已對象數組返回 var row = (sql, ...params) => { return new Promise(function (resolve, reject) { pool.getConnection(function (err, connection) { if (err) { reject(err); return; } connection.query(sql, params, function (error, res) { connection.release(); if (error) { reject(error); return; } resolve(res); }); }); }); }; //返回一個對象 var first = (sql, ...params) => { return new Promise(function (resolve, reject) { pool.getConnection(function (err, connection) { if (err) { reject(err); return; } connection.query(sql, params, function (error, res) { connection.release(); if (error) { reject(error); return; } resolve(res[0] || null); }); }); }); }; //返回單個查詢結果 var single = (sql, ...params) => { return new Promise(function (resolve, reject) { pool.getConnection(function (err, connection) { if (err) { reject(err); return; } connection.query(sql, params, function (error, res) { connection.release(); if (error) { reject(error); return; } for (let i in res[0]) { resolve(res[0][i] || null); return; } resolve(null); }); }); }); } //執行代碼,返回執行結果 var execute = (sql, ...params) => { return new Promise(function (resolve, reject) { // 獲取鏈接 pool.getConnection(function (err, connection) { if (err) { reject(err); return; } // 操做數據庫 connection.query(sql, params, function (error, res) { // 釋放 connection.release(); if (error) { reject(error); return; } resolve(res); }); }); }); } //模塊導出 module.exports = { ROW: row, FIRST: first, SINGLE: single, EXECUTE: execute } /*鏈接mysql*/ function connectToMysql() { var connection = mysql.createConnection({ host: '', user: '', password: '', database: '' }); connection.connect(); //查詢 connection.query('SELECT * FROM user;', function (err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0]); }); //關閉鏈接 connection.end(); }