mysql2简介
MySQL2 项目是 MySQL-Native 的延续。协议解析器代码从头重写,api 更改以匹配流行的 mysqljs/mysql,Node-MySQL2 的目标是取代 node-mysql(github.com/mysqljs/mysql)。mysqll2 团队正与 mysqljs/mysql 团队合作,将共享代码移到 mysqljs 组织下。
MySQL2(https://github.com/sidorares/node-mysql2
) 基本上是与 mysqljs 兼容的 API,并支持大多数特性。mysql 也提供了这些额外的特性:
- Faster / Better Performance(更快/更好的性能)
- Prepared Statements(预处理语句)
- MySQL Binary Log Protocol(二进制日志)
- MySQL Server
- Extended support for Encoding and Collation(对编码和排序的扩展支持)
- Promise Wrapper(Promise 包装器,可直接使用
async/await
语法) - Compression(压缩)
- SSL and Authentication Switch(SSL和认证开关)
- Custom Streams(自定义流)
- Pooling(连接池)
mysql2用例
// app.js
const Koa = require('koa');
const Router = require('koa-router');
const mysql = require('mysql2/promise'); // 安装:npm install --save mysql2
const app = new Koa();
const router = new Router();
app.context.appname = 'koa2';
router.get('/', async (ctx, next) => {
const [rows, fields] = await ctx.connection.query('SELECT * FROM `product_category` WHERE `id` = ? AND `parent_id` < ?', [1, 2]);
ctx.type = 'text/html';
ctx.body = `${ctx.appname}, ${ctx.username}, ${rows[0].category_name}`;
});
app.use(async (ctx, next) => {
const connection = await mysql.createConnection({
host: 'localhost',
user: '******',
password: '******',
database: '******',
charset: 'utf8mb4'
});
ctx.connection = connection;
ctx.username = '许善祥';
await next();
})
.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
})
.use(router.routes())
.use(router.allowedMethods())
.listen('3000',(err)=>{
if(err){
console.log('服仵器启动失败');
}else{
console.log('服务器启动成功');
}
});
扩展
app.use(function)
将给定的中间件方法添加到此应用程序。app.use() 返回 this ,因此可以链式表达。
app.context
app.context 是从其创建 ctx 的原型。您可以通过编辑 app.context 为 ctx 添加其他属性。这对于将 ctx 添加到整个应用程序中使用的属性或方法非常有用,这可能会更加有效(不需要中间件)和/或 更简单(更少的 require()),而更多地依赖于ctx,这可以被认为是一种反模式。
相关源代码 application.js 摘选
…
constructor (options)
{
super()
options = options || {}
this.proxy = options.proxy || false
this.subdomainOffset = options.subdomainOffset || 2
this.proxyIpHeader = options.proxyIpHeader || ‘X-Forwarded-For’
this.maxIpsCount = options.maxIpsCount || 0
this.env = options.env || process.env.NODE_ENV || ‘development’
if (options.keys) this.keys = options.keys
this.middleware = []
this.context = Object.create(context)
this.request = Object.create(request)
this.response = Object.create(response)
// util.inspect.custom support for node 6+
/* istanbul ignore else */
if (util.inspect.custom) {
this[util.inspect.custom] = this.inspect
}
}…
// 初始化一个新上下文createContext (req, res)
{
const context = Object.create(this.context)
const request = context.request = Object.create(this.request)
const response = context.response = Object.create(this.response)
context.app = request.app = response.app = this
context.req = request.req = response.req = req
context.res = request.res = response.res = res
request.ctx = response.ctx = context
request.response = response
response.request = request
context.originalUrl = request.originalUrl = req.url
context.state = {}
return context
}