const Sequelize = require('sequelize');
const sequelize = new Sequelize('数据库名', '数据库账号', '数据库密码', {
host: '主机名',
dialect: 'mysql',
port: '端口',
operatorsAliases: false,
timezone: '+08:00', // 时区,中国+8
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize
.authenticate()
.then(() => {
console.log('***数据库连接成功');
})
.catch(err => {
console.error('数据库连接失败:', err);
});
module.exports = sequelize;
const Sequelize = require('sequelize');
const db =require('./db');
// 创建 model
let 变量名 = db.define('表名', {
字段名: {
type: Sequelize.STRING // string类型
}
});
module.exports = 变量名
模型名.create(data)
.then(createRes => {
res.json({
code: '1',
msg: '创建成功',
data: {
result: createRes
}
})
}
.catch(err => {
console.log(err);
})
模型名.destroy({ where: {id: pid} })
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
模型名.update(data,{ where: {id: pid} })
.then(updateRes => {
res.json({
code: '1',
msg: '修改成功',
data: {
result: updateRes
}
})
})
.catch(err => {
console.log(err);
})
// 查询一个
模型名.findOne({ where: {id: req.query.id} })
.then(respons => {
res.json({
code: '1',
msg: '查询成功',
data: respons
})
})
.catch(errors => {
console.log(errors);
})
// 查询多个
模型名.findAll()
.then(respons => {
res.json({
code: '1',
msg: '查询成功',
data: respons
})
})
.catch(errors => {
console.log(errors);
})
点击查看