sequelize多条件_Sequelize 快速入门

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 方法。两者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值