为了简略,各种软件和库的名称我就不辨别大小写了。
说下为什么应用sqlite,我在抉择sqlite前应用了mysql、mongodb这两款数据库,他们很成熟很弱小,然而配置起来对于老手要费点工夫,思考到我想要开发CMS是一个很轻量的零碎,应用这两个数据库感觉太重了。要害是sqlite性能少学起来也简略。
通常操作数据库都会抉择一个ORM,通过ORM去操作数据库,能够无效防止SQL注入平安问题,操作起来也比间接写SQL简略,这里抉择egg-orm,基于leoric封装的。
首先装置相干依赖
yarn add egg-orm sqlite3 @journeyapps/sqlcipher --save
在plugin中启用插件
module.exports = {
// had enabled by egg
static: {
enable: true,
},
orm: {
enable: true,
package: 'egg-orm',
},
};
在config.default.js中配置数据库信息
// 数据库
const userConfig = {
orm: {
client: '@journeyapps/sqlcipher', // 数据加密
dialect: 'sqlite',
database: appInfo.baseDir + '/database/data.db', // 数据寄存地位
connectionLimit: 10, // 连接池数量
},
}
实现以上配置后,在egg我的项目的app.js中,serverDidReady钩子里设置表模型同步,这样在利用启动后,表会依据模型主动创立和更新
async serverDidReady() {
await this.app.model.sync({ alter: true });
// http / https server 已启动,开始承受内部申请
// 此时能够从 app.server 拿到 server 的实例
}
当初就能够编写代码了,当初model目录中定义一个表构造
module.exports = function(app) {
const { Bone, DataTypes: { STRING, INTEGER } } = app.model;
// console.log(Realm)
class User extends Bone {
static table = 'user'
static attributes = {
name: STRING,
password: STRING,
}
};
return User
}
而后在controller中写增删改查
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async list() {
const { ctx } = this;
const list = await ctx.model.User.find();
console.log(list);
ctx.body = list;
}
async create() {
const { ctx } = this;
await ctx.model.User.create({
password: '123456',
name: 'wmui',
});
ctx.body = {
success: true,
};
}
async update() {
const { ctx } = this.ctx;
const i = await ctx.model.User.update({
name: 'wmui',
}, {
password: '12345678',
});
console.log(i);
ctx.body = {
success: true,
};
}
async remove() {
const { ctx } = this.ctx;
const i = await ctx.model.User.remove({
name: 'wmui',
});
console.log(i);
ctx.body = {
success: true,
};
}
}
module.exports = HomeController;
实现数据库连贯是开始的第一步,前面就能够欢快的实现逻辑了。
如果对egg和sql不太熟悉,下面代码看起来可能有点吃力,能够看下官网的文档简略入手实际一下,egg应用起来很是挺不便的。
发表回复