Sequelize
是一个基于 Promise 的 Node.js ORM,目前支持 Postgres、 MySQL 、SQLite 和 Microsoft SQL Server。它具有强大的事务支持,关联关系、读取和复制等功能。
安装
npm
// Using NPM
$ npm install --save sequelize
# And one of the following:
$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL
yarn
// Using Yarn
$ yarn add sequelize
# And one of the following:
$ yarn add pg pg-hstore
$ yarn add mysql2
$ yarn add sqlite3
$ yarn add tedious // MSSQL
本文所使用的第三方库的版本信息为:”sequelize”: “^4.39.0”、”mysql2”: “^1.6.1”。
建立 数据库 连接
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite'
});
// Or you can simply use a connection uri
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
测试连接
这里以 mysql 数据库为例:
const Sequelize = require('sequelize');
const sequelize = new Sequelize(
'exe', // 数据库名称
'root', // 用户名
'', // 密码
{
host: 'localhost',
dialect: 'mysql', // 'mysql'|'sqlite'|'postgres'|'mssql'
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
需要注意的是,运行以上代码前需保证本机已安装并启动了 mysql。对于使用 MacOS 的小伙伴来说,可以通过 Homebrew
来安装和启动 mysql:
$ brew doctor # 确认 brew 是否正常。
$ brew update # 更新包
$ brew install mysql # 安装 mysql
$ brew services start mysql #启动 mysql
$ brew services restart mysql #重启 mysql
$ brew services stop mysql #关闭 mysql
定义模型
const Sequelize = require("sequelize");
module.exports = sequelize => {
const User = sequelize.define("user", {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
}
});
User.sync({
force: true
}).then(() => {
console.log("User Table has been created");
});
return User;
};
以上示例中 User.sync({force: true})
,将会先删掉表后再建表。当然,你也可以先定义好表结构,再来定义 Sequelize
模型,这时就不需要使用 sync 方法。两者