npm init -y
npm i sequelize mysql2 standard --save
新建一个 db.js
// 引入依赖
let Sequelize = require('sequelize')
// 导出新建的连接数据库实例,方便在其它文件中引用
module.exports = new Sequelize('test', 'root', 'root123', {
// 数据库地址
host: '192.168.5.43',
// 使用的数据库方言
dialect: 'mysql',
pool: {
// 连接池中最大连接数量
max: 5,
// 连接池中最小连接数量
min: 0,
// 超时时间,如果10S中没有使用,那么释放线程
idle: 10000
}
})
使用参数连接,本质上是:
new Sequelize(database, [username=null], [password=null], [options={}])
// 熟悉ES6的同学应该都知道函数的默认参数,这里面除了 database 名是必须的以外,其它的都是使用默认参数的
// 所以我们可以通过这个推理出下面的几种连接方式
没有password 和 options
new Sequelize('database', 'username')
没有 options
new Sequelize('database', 'username', 'password')
没有密码但是有 options
new Sequelize('database', 'username', null, {})
全部都有
new Sequelize('database', 'username', 'password', {})
当然,还有一种特殊的连接方式,那就是直接使用链接,它的本质上是这样的,即 options 有默认参数
new Sequlize(URI, [options={}])
只有 URI 没有 options
new Sequelize('mysql://localhost:3306/database')
全有
new Sequelize('mysql://localhost:3306/database', {})
新建一个 testconnet.js
const conn = require('./db')
// 使用 sequlize 官方提供的 zuthenticate 来测试是否连接,使用的是 Promise 风格
conn.authenticate().then(() => console.log('connected')).catch(err => console.log(err))
const Sequelize = require('sequelize')
const sequelize = require('../db')
// 先定义好对应的实例,如表名, 列名等
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
validate: {
notNull: true
}
},
lastName: {
type: Sequelize.STRING,
validate: {
notNull: true
}
}
})
// 创建表,使用的是 sync 方法,该方法返回一个 Promise 对象,可以使用 then, catch 来进行后续操作
// 该方法有一个参数,那就是 force ,参数为 boolean 型,如果为 true ,那么会删除原表再创建,如果为 false 那么不会删除原表
User.sync({force: true}).then(() => console.log('SUCCESS CREATE TABLE USER')).catch(err => console.log(err))
// 删除表
User.drop()
名称 | 对应数据库 |
---|---|
Sequelize.STRING | VARCHAR(255) |
Sequelize.STRING(1234) | VARCHAR(1234) |
Sequelize.STRING.BINARY | VARCHAR BINARY |
Sequelize.TEXT | TEXT |
Sequelize.TEXT(‘tiny’) | TINYTEXT |
Sequelize.INTEGER | INTEGER |
Sequelize.BIGINT | BIGINT |
Sequelize.BIGINT(11) | BIGINT(11) |
Sequelize.FLOAT | FLOAT |
Sequelize.FLOAT(11) | FLOAT(11) |
Sequelize.FLOAT(11, 12) | FLOAT(11,12) |
Sequelize.DOUBLE | DOUBLE |
Sequelize.DOUBLE(11) | DOUBLE(11) |
Sequelize.DOUBLE(11, 12) | DOUBLE(11,12) |
Sequelize.DECIMAL | DECIMAL |
Sequelize.DECIMAL(10, 2) | DECIMAL(10,2) |
Sequelize.DATE | DATETIME |
Sequelize.DATE(6) | DATETIME(6) |
Sequelize.DATEONLY | DATE without time. |
Sequelize.BOOLEAN | TINYINT(1) |
Sequelize 支持的一些数据类型。 有关完整和更新的列表, 参阅 DataTypes.
属性 | 参数 | 详情 |
---|---|---|
is | [“\^[a-z]+$”,’i’] | 只允许字母 |
is | /\^[a-z]+$/i | 与上一个示例相同,使用了真正的正则表达式 |
not | [“[a-z]”,’i’] | 不允许字母 |
isEmail | true | 检查邮件格式 ([email protected]) |
isUrl | true | 检查连接格式(http://foo.com) |
isIP | true | 检查IPv4(129.89.23.1)或IPv6格式 |
isIPv4 | true | 检查IPv4(129.89.23.1)格式 |
isIPv6 | true | 检查IPv6格式 |
isAlpha | true | 只允许字母 |
isAlphanumeric | true | 只允许使用字母数字 |
isNumeric | true | 只允许数字 |
isInt | true | 检查是否为有效整数 |
isFloat | true | 检查是否为有效浮点数 |
isDecimal | true | 检查是否为任意数字 |
isLowercase | true | 检查是否为小写 |
isUppercase | true | 检查是否为大写 |
notNull | true | 不允许为空 |
isNull | true | 只允许为空 |
notEmpty | true | 不允许空字符串 |
equals | ‘specificvalue’ | 只允许一个特定值 |
contains | ‘foo’ | 检查是否包含特定的子字符串 |
notIn | [[‘foo’,’bar’]] | 检查是否值不是其中之一 |
isIn | [[‘foo’,’bar’]] | 检查是否值是其中之一 |
notContains | ‘bar’ | 不允许包含特定的子字符串 |
len | [2,10] | 只允许长度在2到10之间的值 |
isUUID | 4 | 只允许uuids |
isDate | true | 只允许日期字符串 |
isAfter | “2011-11-05” | 只允许在特定日期之后的日期字符串 |
isBefore | “2011-11-05” | 只允许在特定日期之前的日期字符串 |
max | 23 | 只允许值<=23 |
min | 23 | 只允许值>=23 |
isCreditCard | true | 检查有效的信用卡号码 |
当然也可以写自定义验证规则
isEven(value) {
if (parseInt(value) % 2 != 0) {
throw new Error('Only even values are allowed!')
// 我们也在模型的上下文中,所以如果它存在的话,
// this.otherField会得到otherField的值。
}
}
有关内置验证方法的更多详细信息,请参阅the validator.js project 。
当然很多情况下,数据库中已经事先定义好了表,那么我们再一个个的重复写着 modle 那就没有一点意义,这个时候我们就需要通过 sequelize-auto 来自动生成对应模型
npm i sequelize-auto -g
sequelize-auto -h localhost -d test -u root -x root123 -p 3306
参数 | 含义 |
---|---|
-h | mysql 服务地址 |
-d | 操作的数据库 |
-x | 密码 |
-u | 用户名 |
-p | 接口 |
-t | 要生成的表,如果不填的话,那么生成全部表 |
-T | 不要生成的表 |
sequelize-auto 官方文档
const Sequelize = require('sequelize')
const sequelize = require('../db')
const user = require('./users')
// 然后就可以这么使用了,这样的话就与我们之前自己创建的表操作汉典有任何区别
let User = user(sequelize,Sequelize)
User.sync()
module.exports = User
依旧使用上面创建的 User 表为例
const conn = require('./db')
const User = require('./hand-module/user')
User.create({
firstName: 'Hello',
lastName: 'World'
})
User.create({
firstName: 'Hello',
lastName: 'JavaScript'
})
const conn = require('./db')
const User = require('./hand-module/user')
User.destroy({where: {lastName: 'World'}})
const conn = require('./db')
const User = require('./hand-module/user')
User.update({firstName: 'LOVE'},{where: {firstName: 'Hello'}})
User.findOne({where: {lastName: 'JavaScript'}}).then(data => {
console.log(data.dataValues)
})
User.findAll({where: {firstName: 'LOVE'}}).then(data=>{
for(let i in data){
console.log(data[i].dataValues)
}
})
static-method参考文档