安装
npm install --save sequelize
# 还有以下之一:
npm install --save pg pg-hstore
npm install --save mysql2 // MySQL需要另外装
npm install --save sqlite3
npm install --save tedious // MSSQL
使用
const Sequelize = require('sequelize');
建立连接
var sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost', //数据库地址,默认本机
port: '3306',
dialect: 'mysql',
pool: { //连接池设置
max: 5, //最大连接数
min: 0, //最小连接数
idle: 10000
},
logging: false //阻止sequelize输出到控制台
});
定义模型
模型使用sequelize.define('name', {attributes}, {options}) 来定义.
const add = sequelize.define('addacticle', {
title: {
type: Sequelize.INTEGER,
primaryKey: true, //主键
autoIncrement: true, //自增
comment: "自增id" //注释:只在代码中有效
},
title: {
type: Sequelize.STRING
},
body: {
type: Sequelize.STRING
}
});
初始化表
// force: true 如果表已经存在,将会丢弃表
// alter: true 如果表已存在,不过丢弃,如果不存在会直接创建表
add.sync({ alter: true })
新增数据接口
app.post('/api/articles', async (req, res) => {
const acticle = await add.create(req.body);
res.send(acticle);
});
查询数据接口
app.get('/api/articles', async (req, res) => {
const article = await add.findAll({
attributes: ['title', 'body']
});
res.send(article);
})
资料链接
sequelize 的用法笔记
https://www.jianshu.com/p/066ec657171f
sequelize常见API使用
https://blog.csdn.net/lvyuan1234/article/details/87010463
Sequelize 中文API文档-1. 快速入门、Sequelize类
https://blog.csdn.net/sd19871122/article/details/85221206
官方文档
https://sequelize.org/