var mysql = require('mysql')
// 创建与数据库的链接
var connection = mysql.createConnection({
host: 'example.com',
user: 'example',
password: 'secret-password'
})
// 经过 mysql提供的接口进行查询
connection.query('SELECT * FROM project WHERE id = ?', ['1'], function( err, rows ) {
if (err) {
// error
} else {
for (let row in rows) {
// 业务代码
}
}
})
复制代码
Table projectjavascript
名称 | 类型 | 容许空 | 默认值 | 主键 | 说明 |
---|---|---|---|---|---|
id | int(11) | Y | - | Y | |
content | text | Y | - | N | 项目描述 |
title | varchar(90) | Y | - | N | 项目名称 |
priority_status | int(11) | Y | 1 | N | 优先级id |
owner | int(11) | Y | 0 | N | 项目经理(PM)id |
team_id | int(11) | Y | 0 | N | 小组id |
process_status | vint(11) | Y | - | N | 项目状态 |
schedule | double(11, 2) | Y | 0.00 | N | 项目进度 |
prepayDate | date | Y | - | N | 预交时间 |
createDate | date | Y | - | N | 建立时间 |
deadline | date | Y | - | N | 截止时间 |
// 就能够映射为,表中每一列映射为对象中一个键值对,每一行映射为一个js对象。
{
id:'',
content:'',
title:'',
priority_status:'',
priority_status:'',
owner:''
...
}
复制代码
创建数据库链接html
let Sequelize = require("sequelize");
let sequelize = new Sequelize(
'sample', // 数据库名
'root', // 用户名
'password', // 用户密码
{
dialect: 'mysql', // 数据库使用mysql
host: 'localhost', // 数据库服务器ip
port: 3306, // mysql默认端口
define: {
'underscored': true // 字段如下划线(_)来分割(默认是驼峰命名风格)
},
pool: {
max: 20, // 链接池最大链接数量
min: 0, // 链接池最小链接数量
idle: 10000 // 每一个线程最长等待时间
}
}
);
// freezeTableName: true,
复制代码
定义模型java
// public define(modelName: String, attributes: Object, options: Object): Model
// modelName:模型名称,自定义 attributes:模型中包含都数据,每个数据映射对应表中都每个字段 options:模型(表)的设置
var project = sequelize.define(
'project', // 默认表名(通常这里写单数),生成时会自动转换成复数形式。在模型访问时的model.name
{
id: {
type: Sequelize.INTEGER(11), // 字段类型
allowNull: false, // 是否容许为NULL
primaryKey: true, // 字段是主键
autoIncrement: true, // 是否自增
},
content: {
type: Sequelize.TEXT,
allowNull: true,
unique: false // 字段是否UNIQUE
},
title: {
type: Sequelize.STRING(90),
allowNull: true,
validate: { //模型验证 当前字段值发生改变的时候进行验证
is: ["^[a-z]+$",'i'], // 只容许字母
not: ["[a-z]",'i'], // 不能使用字母
isEmail: true
},
field: 'project_title' // 数据库中字段的实际名称
}
},
{
tableName: 'project', // 手动设置表的实际名称
timestamps: false, // 是否给每条记录添加 createdAt 和 updatedAt 字段,并在添加新数据和更新数据的时候自动设置这两个字段的值,默认为true
paranoid: true, // 设置 deletedAt 字段,当删除一条记录的时候,并非真的销毁记录,而是经过该字段来标示,即保留数据,进行假删除,默认为false
freezeTableName: false, // 禁用修改表名; 默认状况下,sequelize将自动将全部传递的模型名称(define的第一个参数)转换为复数。 默认为false
indexes: [] // 定义表索引
}
)
// 表同步:没有就新建,有就不变
// project.sync();
// 表同步:没有就新建,有就先删除再新建
// project.sync({
// force: true
// });
复制代码
增node
// 建立模型实例对象 public static build(options: Object): Model | Model[]
// options:一个对象,对应的就是表中的字段(模型中定义的属性),须要注意的是对该对象的操做不会当即反应到实际的数据库中,须要经过后续的操做进行同步好比save
attr= {
id:"test",
content:"iscontent",
titile:"istitle"
}
let projectInstance = Project.build(attr) // 建立实例对象
// 实例方法
projectInstance.save() // 验证该实例,若是经过验证,则持久化到数据库中
projectInstance.update(updates: Object) // updates:要更新的字段,调用该方法等同于调用.set()而后.save()
projectInstance.destroy() // 销毁该实例(假删除或真删除)
// public static create(values: Object, options: Object): Promise<Model>
// 构建一个新的模型实例,并进行保存。与build()方法不一样的是,此方法除建立新实例外,还会将其保存到对应数据库表中。
await Project.create(attr)
复制代码
查mysql
// 根据主键搜索单条记录: 模型.findById(id: Number | String | Buffer)
Project.findById(1);
// 根据条件搜索一条记录: 模型.findOne(options: Object)
Project.findOne({
where:{id:1}
});
//搜索特定记录或建立它(若是没有对应记录): 模型.findOrCreate(options: Object)
//在数据库中搜索多个记录,返回数据和总计数: 模型.findAll(findOptions: Object)
Project.findAll({
where: { id:1, content: 'iscontent' }, // 搜索条件
limit: 10, // 查询记录条数限制
offset: 2, // 查询时的偏移/起始位置,通常用于分页查询时
order: [
"id", //根据id排序
["id","desc"] //根据id倒序
],
attributes:["title","owner"], //返回的字段
})
// 在数据库中搜索多个记录,返回数据和总计数: 模型.findAndCountAll(findOptions: Object)
// 与findAll相似,可是返回值包含 count 属性 - 返回数据与总计数
let result = await Project.findAndCountAll({
'limit': 20,
'offset': 0
});
// 返回的result对象将包含2个字段:result.count是数据总数,result.rows是符合查询条件的全部数据。
复制代码
// 限制查询结果对象中的字段
let result = await Project.findAndCountAll({
attributes:["title","owner"],
});
// => { title: 'istitle', owner: 1 } 而不是返回全部的字段
// 字段重命名
let result = await Project.findAndCountAll({
attributes:[ ["title","projectTitle" ],"owner"],
});
// => { projectTitle: 'istitle', owner: 1 } 而不是返回全部的字段
// where 子句
let result = await Project.findAndCountAll({
where:{
id: [1, 2, 3],
title: 'a',
content: 'iscontent'
}
});
// 查询projects表中知足 (id ===1 || id ===2 || id ===3) && title === 'a' && content === 'iscontent' 条件的记录
// 复合过滤
const Op = Sequelize.Op
Project.findAll({
where: {
title: 'a',
id: { [Op.eq]: 1 }, // id为1
[Op.or]: [{ priority_status: [1, 2] }, { owner: { [Op.gt]: 10 } }] // (priority_status === 1 ||priority_status === 2)&& owner > 10
}
})
// [常见的Op及解释][5]
[Op.and]: {a: 5} // 且 (a = 5)
[Op.or]: [{a: 5}, {a: 6}] // (a = 5 或 a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.eq]: 3, // = 3
[Op.not]: true, // 不是 TRUE
[Op.between]: [6, 10], // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2], // 在 [1, 2] 之中
[Op.notIn]: [1, 2], // 不在 [1, 2] 之中
[Op.like]: '%hat', // 包含 '%hat'
[Op.notLike]: '%hat' // 不包含 '%hat'
[Op.iLike]: '%hat' // 包含 '%hat' (不区分大小写) (仅限 PG)
[Op.notILike]: '%hat' // 不包含 '%hat' (仅限 PG)
[Op.regexp]: '^[h|a|t]' // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 一样适用于 iLike 和 notLike
[Op.overlap]: [1, 2] // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2] // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2] // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3] // 任何数组[2, 3]::INTEGER (仅限PG)
复制代码
改正则表达式
// public static update(values: Object, options: Object): Promise<Array<affectedCount, affectedRows>>
const result = await Project.update(
{
content: "newContent"
},
{
where: {
id: projectId,
user_id: userId
}
}
)
复制代码
删sql
// public destroy(options: Object): Promise<undefined>
const result = await Project.destroy({
where: {
id: projectId,
user_id: userId
}
})
复制代码