使用egg.js和egg-sequelize连接mysql
egg-init --type=simple --dir=sequelize-project
cd sequelize-project
npm i
2.安装并配置 egg-sequelize 插件(它会辅助我们将定义好的 Model 对象加载到 app 和 ctx 上)和 mysql2模块:
3.
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
-
在 配置数据库信息(在
config/config.default.js
中添加 sequelize 配置)
/* eslint valid-jsdoc: "off" */ 'use strict'; /** * @param {Egg.EggAppInfo} appInfo app info */ module.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1553528793275_7075'; // add your middleware config here config.middleware = []; config.sequelize = { dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'egg_test', //数据库民 username: 'root', //数据库的用户名 password: 'root' // } // add your user config here const userConfig = { // myAppName: 'egg', }; return { ...config, ...userConfig, }; };
使用model 连接数据表
Model/user.js
'use strict'; module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('user', { userid: { type: INTEGER, primaryKey: true, autoIncrement: true }, username: STRING(50), sex: STRING(4), userpass:STRING(32) }, { freezeTableName: true, // Model 对应的表名将与model名相同 timestamps: false, } ); return User; };
5.调用model操作数据库
controller/user.js
'use strict'; const Controller = require('egg').Controller; class HomeController extends Controller { async index() { const { ctx } = this; ctx.body = 'hi, egg'; } } module.exports = HomeController;
6.创建数据库
ALTER TABLE `user` MODIFY COLUMN `userid` int(11) NOT NULL DEFAULT '' FIRST , MODIFY COLUMN `sex` char(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' AFTER `username`;
7.添加路由
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); router.get('/user', controller.user.index); };
越努力越幸运