安装模块sequelize和mysql2
1.config.js
var config = {
database: 'mysql',
username: 'username',
password: '*****',
host: 'localhost',
port: 3306
};
module.exports = config;
2.app.js
const Sequelize = require('sequelize');
const config = require('./config');
var sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: 'mysql',
pool: {
max: 6,
min: 0,
idle: 50000
}
});
//定义一个序列号模型,对应于mysql数据库中的pets表,字段要一致
var Pet = sequelize.define('pet', {
id: {
type: Sequelize.STRING(50),
primaryKey: true
},
name: Sequelize.STRING(100),
gender: Sequelize.BOOLEAN,
birth: Sequelize.STRING(10),
createdAt: Sequelize.BIGINT,
updatedAt: Sequelize.BIGINT,
version: Sequelize.BIGINT
}, {
timestamps: false
});
var now = Date.now();
//使用promise方式插入一条记录
Pet.create({
id: 'g-' + now,
name: 'Gaffey',
gender: false,
birth: '2018-07-07',
createdAt: now,
updatedAt: now,
version: 0
}).then(function (p) {
console.log('created.' + JSON.stringify(p));
}).catch(function (err) {
console.log('failed: ' + err);
});
//使用await方式插入一条记录
(async () => {
var dog = await Pet.create({
id: 'd-' + now,
name: 'Odie',
gender: false,
birth: '2019-03-08',
createdAt: now,
updatedAt: now,
version: 0
});
console.log('created: ' + JSON.stringify(dog));
})();
//查询数据
(async () => {
var pets = await Pet.findAll({
where: {
name: 'Gaffey'
}
});
console.log(`find ${pets.length} pets:`);
for (let p of pets) {
console.log(JSON.stringify(p));
console.log('update pet...');
p.gender = true;
p.updatedAt = Date.now();
p.version ++;
await p.save(); //更新数据
if (p.version === 3) {
await p.destroy(); //删除数据
console.log(`${p.name} was destroyed.`);
}
}
})();