截止到今天,mysqljs在github上已經獲取到了10000+star了,能夠說是實實在在最流行的mysql驅動了,可是要把mysqljs應用到koa2中,彷佛不太方便,koa2使用最新的語法async, await,而mysqljs,卻還停留在callback階段。mysql
今天這篇文章就是要解決這個問題,很是簡單。git
一、實際開發中,咱們確定是使用鏈接池的形式,因此,咱們選擇了mysql.createPool這個方法:github
var mysql = require('mysql'); var pool = mysql.createPool(...); pool.getConnection(function(err, connection) { // Use the connection connection.query('SELECT something FROM sometable', function (error, results, fields) { // And done with the connection. connection.release(); // Handle error after the release. if (error) throw error; // Don't use the connection here, it has been returned to the pool. }); });
二、使用Promise,對上面的方法稍加改造便可:sql
var mysql = require('mysql'); var pool = mysql.createPool(...); const q = function (sql, values) { return new Promise((resolve, reject) => { pool.getConnection((err, conn) => { if (err) return reject(err) conn.query(sql, values, (err, rows) => { if (err) reject(err) else resolve(rows) conn.release() }) }) }) }
通過以上封裝,一個查詢用戶信息的操做就能夠這樣優雅的完成了:
async function getUserInfoById(id) { let userInfo = await q('select * from user where id=?', [id]) console.log(userInfo) }
三、受tornado的一個mysql操做庫torndb的啓發,能夠這樣作一個完整的封裝:數據庫
const mysql = require('mysql') const defautConfig = { host: 'localhost', user: 'root', password: '', database: 'test', connectionLimit: 20 } const AsyncMysqljs = function(config=defautConfig){ const pool = mysql.createPool(config) const q = function (sql, values) { return new Promise((resolve, reject) => { pool.getConnection((err, conn) => { if (err) return reject(err) conn.query(sql, values, (err, rows) => { if (err) reject(err) else resolve(rows) conn.release() }) }) }) } /* 從數據庫中查詢一條數據,返回值是對象,而非數組 最好在sql語句中加一個惟一的限制條件 */ const get = (sql, values) => { try { return q(sql, values).then(rows => { if (rows.length >= 1) { return rows[0] } }) } catch (err) { return new Promise((resolve, reject) => { reject(err) }) } } return {query: q, delete: q, update: q, insert: q, execute: q, get} } module.exports = AsyncMysqljs
具體代碼請查看個人github項目asyncmysqljs,歡迎給建議或者star。數組