全棧專案|小書架|伺服器開發-NodeJS 中使用 Sequelize 操作 MySQL資料庫
阿新 • • 發佈:2019-12-31
安裝
安裝sequelize
及資料庫連線驅動
npm install --save sequelize
$ npm install --save mysql2
複製程式碼
使用
建立連線:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database','username','password',{
host: 'localhost',dialect: 'mysql'
});
複製程式碼
建立Model表:
const Model = Sequelize.Model;
class User extends Model {}
User.init({
// attributes
firstName: {
type : Sequelize.STRING,allowNull: false
},lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
},{
sequelize,modelName: 'user'
// options
});
複製程式碼
生產資料:
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model definition
return User.create({
firstName: 'John',lastName: 'Hancock'
});
});
複製程式碼
增加資料
// Create a new user
User.create({ firstName: "Jane",lastName: "Doe" }).then(jane => {
console.log("Jane's auto-generated ID:",jane.id);
});
複製程式碼
刪除資料
// Delete everyone named "Jane"
User.destroy({
where: {
firstName: "Jane"
}
}).then(() => {
console.log("Done");
});
複製程式碼
改變資料
// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" },{
where: {
lastName: null
}
}).then(() => {
console.log("Done");
});
複製程式碼
查詢資料
// Find all users
User.findAll().then(users => {
console.log("All users:",JSON.stringify(users,null,4));
});
複製程式碼
資料型別
Model 使用
Model 查詢
資料遷移
對於資料遷移這塊,筆者目前實際使用還是不熟練,比如 model
添加了新的欄位如何處理、開發環境和生產環境新新增欄位或者刪除欄位怎麼處理 ,希望有熟悉的朋友能夠指導一二,不勝感激。
諮詢請加微信:輕撩即可。