參考自 Sequelize 的官方文檔
未完
1. 引入
--- npm 安裝
$ npm install sequelize --save
同時(shí)需要安裝 數(shù)據(jù)庫(kù)
# 還需要安裝以下之一:
$ npm install --save pg pg-hstore // postgreSql
$ npm install --save mysql2 // mysql 或 mariadb
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL
--- require 引入使用
const Sequelize = require("sequelize");
2. 連接數(shù)據(jù)庫(kù)
// new 一個(gè)實(shí)例 new Sequelize({database,username,password,host,pool,})
this.sequelize = new Sequelize({
database: database, //數(shù)據(jù)庫(kù)名稱(chēng)
username: username, //數(shù)據(jù)庫(kù)用戶名
password: password, //數(shù)據(jù)庫(kù)密碼
host: host, //數(shù)據(jù)庫(kù)主機(jī)IP localhost
dialect: "mysql", //數(shù)據(jù)庫(kù)類(lèi)型 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
pool: { //連接池配置
max: 5, //最大連接數(shù)
min: 0, //最小連接數(shù)
acquire: aquireTimeout, //請(qǐng)求超時(shí)時(shí)間
idle: 10000 //斷開(kāi)連接后聚请,連接實(shí)例在連接池保持的時(shí)間
},
logging: this.logging //輸出日志信息 true or false
});
驗(yàn)證連接上數(shù)據(jù)庫(kù)
this.sequelize
.authenticate()
.then(() => {
console.log("連接建立成功");
resolve();
})
.catch(err => {
reject();
throw new Error(`無(wú)法連接數(shù)據(jù)庫(kù):${err.message}`);
});
部分參數(shù)
Name | Attribute |
---|---|
database | 數(shù)據(jù)庫(kù)名 |
username | 數(shù)據(jù)庫(kù)用戶名. |
password | 密碼 |
dialect | 數(shù)據(jù)庫(kù)方式 |
timezone | 時(shí)區(qū) 默認(rèn)'+00:00' |
logging | 日志 |
pool | 連接池 min max idle |
3. 創(chuàng)建表
public define(modelName: String, attributes: Object, options: Object):
this.tableModels.Users = this.sequelize.define('users', {
mail: {
type: Sequelize.STRING, //數(shù)據(jù)類(lèi)型 STRING,CHAR,INTEGER,FLOAT,FLOAT ,BOOLEAN,TEXT(不限長(zhǎng)度)
primaryKey: true, // 主鍵 默認(rèn)false
allowNull: false, // 是否可以為空 默認(rèn)true
defaultValue: ' 33'
},
name: { type: Sequelize.STRING, allowNull: false },
password: { type: Sequelize.STRING(255) },
authority: { type: Sequelize.INTEGER(1).UNSIGNED,values: ["1", "8"], }
}, {
freezeTableName: true
});
把表同步到數(shù)據(jù)庫(kù)
public sync(options: Object): Promise
this.tableModels.Users.sync({
force:true, // 如果表存在 則刪除表后重建
logging:true // 日志
});
表關(guān)系
BelongsTo,BelongsToMany,HasMany,HasOne
4. 插入數(shù)據(jù)
public static bulkCreate(records: Array, options: Object): Promise<Array<>>
this.tableModels.Users.bulkCreate([
{mail:'183..@163.com',name:'張三',password:'123',authority:'1'},
{mail:'183..@163.com',name:'張三',password:'123',authority:'1'}
])
5. 查詢數(shù)據(jù)
findAll()
findOne()
6 更新數(shù)據(jù)
update()