koa2快速搭建项目
npm install -g koa-generator
koa2 -e weibo-demo //创建个项目
sql语句
查询: select * from users; //查询users表
查询: select username, nickname from users; //查询users表中的username和nickname信息
插入: insert into users (username, ‘password’, nickname) values (‘zhangsan’, 123, ‘张三’); //向users表中插入一条信息
查询模拟登录: select username, nickname from users where username=’zhangsan’ and ‘password’ =’1234’
更新: update blogs set content=’内容’ where id=1
删除: delete from bolgs where id=4
排序: select * from blogs order by id desc //倒序
查询总数: select count( * ) as count from blogs; // * 代表查询所有的列,as为取个别名,* 性能不高,可以改为 select count( id ) as count from blogs;
分页查询: select * from blogs order by id desc limit 2; //查询第一页,每页两行数据
select * from blogs order by id desc limit 2 offset 2; //查询第二页
添加外键-级联删除: 例如blogs表中的userid关联用户表中的用户id,要对userid进行约束,必须是在用户表中存在的,才是合法的,通过添加外键进行限制
连表查询: select * from blogs inner join users on users.id = blogs.userid;
select blogs.* , users.username, users.nickname from blogs inner join users on users.id = blogs.userid where users.username='zhangsan';
联表查询不是必须要有外键约束
sequelize
ORM框架 - Object Relational Mapping 对象关系映射,用来操作数据库
ORM知识点:
- 数据表,用JS中到模型(class或对象)代替
- 一条或多条记录,用JS中一个对象或数组代替
- sql语句,用对象方法代替
建模(外键)& 同步到数据库
npm install mysql2 sequelize -d
mysql2功能类似于mysql,只不过是用法更加简洁
连接数据库
sequelize.js
const Sequelize = require('sequelize')
const conf = {
host: 'localhost',
dialect: 'mysql'
}
// 线上环境,使用连接池
// conf.pool = {
// max: 5, // 连接池中最大的连接数量
// min: 0, // 最小
// idle: 10000, // 如果一个连接池 10s 之内没有被使用,则释放
// }
const seq = new Sequelize('koa2_weibo_db', 'root', 'chen1314', conf)
module.exports = seq
创建模型
model.js
const Sequelize = require('sequelize')
const seq = require('./sequelize')
// 创建 user 模型,数据表到名字是 users
const User = seq.define('user', {
// id 会自动创建,并设为主键,自增
userName: {
type: Sequelize.STRING, // varchar(255)
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
nickName: {
type: Sequelize.STRING,
comment: '昵称' // 通过 comment 添加注释
}
// 自动创建 createAt 和 updateAt
})
// 创建 Blog 模型
const Blog = seq.define('blog', {
// id 会自动创建,并设为主键,自增
title: {
type: Sequelize.STRING,
allowNull: false
},
content: {
type: Sequelize.TEXT,
allowNull: false
},
userId: {
type: Sequelize.INTEGER,
allowNull: false
}
// 自动创建 createAt 和 updateAt
})
// 外键关联
Blog.belongsTo(User, {
// 创建外键 Blog.userId => User.id
foreignKey: 'userId'
})
// 等同于=============
User.hasMany(Blog, {
// 创建外键 Blog.userId => User.id
foreignKey: 'userId'
})
module.exports = {
User,
Blog
}
执行同步
sync.js
const seq = require('./sequelize')
require('./model')
//测试连接
seq.authenticate().then(() => {
console.log('ok');
}).catch(()=> {
console.log('err');
})
//执行同步
seq.sync({ force: true }).then(() => {
console.log("sync ok")
process.exit()
})
增删改查 & 连表查询
向表中添加数据
create.js
const {User, Blog} = require('./model')
!(async function() {
const zhangsan = await User.create({
userName: 'zhangsan',
password: '123',
nickName: '张三'
})
const zhangsanId = zhangsan.dataValues.id
const lisi = await User.create({
userName: 'lisi',
password: '123',
nickName: '李四'
})
const lisiId = lisi.dataValues.id
const blog1 = await Blog.create({
title: '标题一',
content: '内容一',
userId: zhangsanId
})
})()
查询数据
select.js
const {User, Blog} = require('./model')
!(async function() {
// 查询一条记录
const zhangsan = await User.findOne({
where: {
userName: 'zhangsan'
}
})
console.log(zhangsan.dataValues);
// 查询特定对列
const zhangsanName = await User.findOne({
attributes: ['userName', 'nickName'],
where: {
userName: 'zhangsan'
}
})
console.log(zhangsanName.dataValues);
// 查询一个列表
const zhangsanBlogList = await Blog.findAll({
where: {
userId: 1
},
order: [
['id', 'desc']
]
})
console.log(
'zhangsanBlogList',
zhangsanBlogList.map(blog=>blog.dataValues)
);
// 分页
const blogPageList = await Blog.findAll({
limit: 2, // 限制本次查询2条,每页2条
offset: 0, // 跳过多少条,第一页
order: [
['id', 'desc']
]
})
console.log(
'blogPageList',
blogPageList.map(blog=>blog.dataValues)
);
// 查询总数
const blogPageListAndCount = await Blog.findAndCountAll({
limit: 2, // 限制本次查询2条,每页2条
offset: 0, // 跳过多少条,第一页
order: [
['id', 'desc']
]
})
console.log(
'blogPageListAndCount',
blogPageListAndCount.count,
blogPageListAndCount.rows.map(blog=>blog.dataValues)
);
// 连表查询1
const blogListWithUser = await Blog.findAndCountAll({
order: [
['id', 'desc']
],
include: [
{
model: User,
attributes: ['userName', 'nickName'], // 查询属性userName和nickname
where: {
userName: 'zhangsan' //指定查询zhangsan这个用户
}
}
]
})
console.log(
'blogListWithUser',
blogListWithUser.count,
blogListWithUser.rows.map(blog => {
const blogVal = blog.dataValues
blogVal.user = blogVal.user.dataValues
return blogVal
})
);
//连表查询2
const userListWithBlog = await User.findAndCountAll({
attributes: ['userName', 'nickName'],
include: [
{
model: Blog
}
]
})
console.log(
'userListWithBlog',
userListWithBlog.count,
userListWithBlog.rows.map(user => {
const userVal = user.dataValues
userVal.blogs = userVal.blogs.map(blog=>blog.dataValues)
return userVal
})
);
// 修改
const updateRes = await User.update({
nickName: '张三1111'
}, {
where: {
userName: 'zhangsan'
}
})
console.log(updateRes[0] > 0);
// 删除一条博客
const delBlogRes = await Blog.destroy({
where: {
id: 3
}
})
console.log(delBlogRes>0);
// 删除一个用户
// 注意外键
const delUserRes = await User.destroy({
where: {
id: 1
}
})
console.log(delUserRes>0);
})()