使用 Mysql
zKing 2018-11-28 Koa
既然已经能搭起服务了,那就要考虑数据存储了。关系型数据库的话以 Mysql
为例
本文不讲如何去配置 Mysql
,而是讲如何通过 Koa
来连接并使用数据库,这里使用 npm 的 ORM 模块sequelize
来简单地做个示例,献上文档
cnpm install mysql2 -D
cnpm install sequelize -D
dbConfig.js
module.exports = {
host:'localhost',
port:3306,
user:'test',
password:'123456',
database:'comang',
}
model.js
const Sequelize = require('sequelize');
const dbConfig = require('./dbConfig');
// 连接数据库
var sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 30000
},
operatorsAliases: false,
});
// 定义模型
var model = sequelize.define('order', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
goodsname: Sequelize.STRING,
price: Sequelize.DOUBLE,
amount: Sequelize.INTEGER,
ordertime: Sequelize.DATE,
}, {
timestamps: false
});
module.exports = model;
app.js
const model = require('./model');
app.use(async (ctx, next) => {
let list = await model.findAll();
for(let e of list){
console.log(e.goodsname);
}
ctx.body = JSON.stringify(list);
});