koa-连接mysql数据库

koa-连接mysql数据库

koa-1.png

安装数据库插件

npm install mysql -s

default.js编写:

// 数据库配置
const config = {
    port: 3000,  // koa运行端口
    database:{
        DATABASE: '****',    //数据库
        USERNAME: '****',    //用户
        PASSWORD: '****',     //密码
        PORT: '3306',        //端口
        HOST: '******'     //服务ip地址
    }
}

module.exports = config

mysql .js 编写:

一个执行mysql处理的函数

const mysql = require('mysql')
const config = require('./default')

var pool  = mysql.createPool({
    host     : config.database.HOST,
    user     : config.database.USERNAME,
    password : config.database.PASSWORD,
    database : config.database.DATABASE
});

let query = function( sql, values ) {
    return new Promise(( resolve, reject ) => {
        pool.getConnection(function(err, connection) {
            if (err) {
                resolve( err )
            } else {
                connection.query(sql, values, ( err, rows) => {
                    if ( err ) {
                        reject( err )
                    } else {
                        resolve( rows )
                    }
                    connection.release()
                })
            }
        })
    })
}

// 查询hez数据库
let findHez1 = function () {
    let _sql = `SELECT * FROM test `
    return query(_sql)
}
//暴露方法
module.exports={findHez1}

编辑一个路由,验证是否连成功

const Koa = require('koa');
const config = require('./config/default');
const mysql = require('./mysql');
const app =  new Koa();

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
});

app.use(async (ctx) => {
    let request = ctx.request;
    let data = await mysql.query("members");
    console.log(request.origin);
    console.log(request.href);

    ctx.body = {
        "state": true,
        "data": data,
    }
});

app.listen(config.port);
console.log(`listening on port ${config.port}`);

启动服务

node index.js

images-koa.png

Last modification:November 13th, 2019 at 09:17 am
If you think my article is useful to you, please feel free to appreciate

One comment

  1. 与子成说

    希望与贵站交换友情链接www.vrrw.net 谢谢

Leave a Comment