1. 程式人生 > >mysql與koa

mysql與koa

span sel box ise pre lar connect creat ports

/**

* Created by db on 2018/7/20
*/
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


mysql與koa