- 安装
npm install --save sequelize - 安装驱动
One of the following:
npm install --save mysql2 //这个比较多
npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
- 链接数据库
const sequelize = new Sequelize('库名', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
});
中文文档:https://www.sequelize.com.cn/core-concepts/model-querying-basics - 链接测试
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
}); - 建立模型 //就是查找的格式
const Article = sequelize.define('article', {
title: {
type: Sequelize.STRING
}
}, {
freezeTableName: true,
timestamps: false,
});
- 查询
router.get('/Article', async ctx => {
ctx.body = await Article.findAll()
})
- 插入数据
第一种方法 // const jane = Article.build({ title: "C程9" });
// await jane.save();
第二种方法(常用) const jane = await Article.create({ title: "Jane" });
router.post('/issue', async ctx => {
console.log("ctx.request.body", ctx.request.body)
console.log("ctx.request.files", ctx.request.files) //文件
console.log("ctx.request.fields", ctx.request.fields) //表单
let { title, catalogs, tags, contents } = ctx.request.fields
console.log(title, catalogs, tags, contents)
Article.create({ title: title, catalogs: catalogs, tags: tags, content: contents })
})
- 删除数据
router.post('/problem/catalog/delete/id', async ctx => {
let { id } = ctx.request.fields
Catalog.destroy({ where: { ID: id } })
ctx.response = 'success'
})
- 更新数据
const jane = await User.create({ name: "Jane" });
console.log(jane.name); // "Jane"
jane.name = "Ada";
// 数据库中的名称仍然是 "Jane"
await jane.save();
// 现在该名称已在数据库中更新为 "Ada"!
-删除
const jane = await Article.create({ name: "Jane" });
console.log(jane.name); // "Jane"
await jane.destroy();
// 现在该条目已从数据库中删除
- 重载
const jane = await Article.create({ name: "Jane" });
console.log(jane.name); // "Jane"
jane.name = "Ada";// 数据库中的名称依然是 "Jane"await jane.reload();console.log(jane.name); // "Jane"
reload 调用生成一个 SELECT
查询,以从数据库中获取最新数据.