1.安装mysql支持:
npm install mysql --save-dev
2.安装sequelize
npm install sequelize --save-dev
3.创建ORM对象
var Sequelize = require('sequelize'); var sequelize = new Sequelize('kameng', 'root', 'root', { host: '127.0.0.1', dialect: 'mysql' });
4.操作数据库
var router = require('koa-router')(); var Sequelize = require('sequelize'); var sequelize = new Sequelize('kameng', 'root', 'root', { host: '127.0.0.1', dialect: 'mysql' }); // 可以分开写,下面的 var Users = sequelize.define('users', { //id: {type:Sequelize.BIGINT,primaryKey: true}, //uid:{type:Sequelize.BIGINT,primaryKey: true}, email: Sequelize.STRING, pwd: Sequelize.STRING, nicheng: Sequelize.STRING, createtime:Sequelize.DATE, updtime:Sequelize.DATE, role:Sequelize.INTEGER },{ timestamps: false, //paranoid: true //获取不到id的返回值 });
5.在路由下添加如下代码
router.get('/', function *(next) { let user = { email: 'bb', pwd: 'bb', nicheng: 'bb', updtime:new Date(), role:0 }; // Users.create(user).then(function(result){ // console.log(result); // console.log(user); // }).catch(function(err){ // console.log('例外'); // console.log(err.message); // }); try{ let rs = yield Users.create(user); console.log('成功'); console.log(rs); console.log(rs.dataValues.id); }catch(err){ console.log(err.errors[0].message); //识别唯一键 } this.body='koa1'; // yield this.render('index', { // title: 'Hello World Koa!' // }); }); module.exports = router;