# 安装sequelize
npm install --save sequelize
1
# 安装数据库驱动
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
1
2
3
4
5
6
2
3
4
5
6
# 引入sequelize模块
var Sequelize = require('sequelize');
1
# 连接数据库
var sequelize = new Sequelize(
'sample', // 数据库名
'root', // 用户名
'psw', // 用户密码
{
'dialect': 'mysql', // 数据库使用mysql
'host': 'localhost', // 数据库服务器ip
'port': 3306, // 数据库服务器端口
'define': {
// 字段以下划线(_)来分割(默认是驼峰命名风格)
'underscored': true
}
}
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 定义表
var User = sequelize.define(
"user",
{
userId: {
field: "user_id", //自定义列名
primaryKey: true, //主键
type: Sequelize.BIGINT, //类型
allowNull: false, //是否为空
},
userName: {
field: "user_name",
type: Sequelize.STRING,
allowNull: false,
},
userIcon: {
field: "user_icon",
type: Sequelize.STRING,
allowNull: true,
},
title: {
field: "title",
type: Sequelize.STRING,
allowNull: true,
},
gender: {
field: "gender",
type: Sequelize.ENUM("MALE", "FEMALE"),
allowNull: true,
},
birth: {
field: "birth",
type: Sequelize.STRING,
allowNull: true,
},
mail: {
field: "mail",
type: Sequelize.STRING,
allowNull: true,
},
tel: {
field: "tel",
type: Sequelize.STRING,
allowNull: true,
},
mobile: {
field: "mobile",
type: Sequelize.STRING,
allowNull: true,
},
updateTime: {
field: "update_time",
type: Sequelize.STRING,
allowNull: true,
},
},
{
tableName: "user", //表名
timestamps: false, //时间戳更新
freezeTableName: true, //冻结表名自动负复数化
}
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 往表里添加数据
User.create({
userId: 23,
userName: '老杨',
updateTime: '2016-01-22 18:37:22'
});
1
2
3
4
5
6
2
3
4
5
6
# 修改表内数据
var pram = { userName: "晓博" };
user.update(pram, {
where: { userId: { eq: 23 } },
}); //将userId等于23的userName改为'晓博'
1
2
3
4
5
6
2
3
4
5
6
# 删除表内数据
user.destroy({'where':{'id':{eq:23}}});//将表内userId等于23的元组删除
1