node中使用sequelize操作mysql数据库

it2023-10-04  70

1.新建一个文件夹 2.在终端运行 node init -y 3.安装 npm install mysql2 sequelize -d 4.创建src文件夹并在里面创建seq.js文件 seq.js内容

const Sequelize = require('sequelize'); const conf = { host: "localhost", dialect: "mysql" } //线上环境搭建使用连接池的方法 // conf.pool={ // max:5, //连接池中最大的连接数量 占用内存 // min:0, //连接池中最小的连接数量 // idle:10000 //如果一个连接池 10s 之内没有被使用,则释放 // } // 数据表名称 mysql账户 mysql密码 const seq = new Sequelize('koa2_weibo_db', 'root', 'root', conf); // 测试连接 // seq.authenticate().then(() => { // console.log('ok') // }).catch(() => { // console.log('err') // }) // 输出实例 module.exports = seq;

连接数据库成功!

6.在src文件夹下创建model.js当做创建数据的模型 建立外键和关联

const Sequelize = require('sequelize') const seq = require('./seq') // 创建 user 模型 //这里写的是user但导进数据库的时候数据库表名自动变成users const User = seq.define('user', { // id 会自动创建,并设为主键、自动增加 userName: { type: Sequelize.STRING,//对应数据库为varchar(255) allowNull: false,//不能为空 comment: "用户名" }, password: { type: Sequelize.STRING, allowNull: false, comment: "密码" }, nickName: { type: Sequelize.STRING, comment: "昵称" } // 会自动创建:createdAt 和 updatedAt }) // 创建 Blog 模型 const Blog = seq.define('blog', { title: { type: Sequelize.STRING, allowNull: false, comment: "文章标题" }, content: { type: Sequelize.TEXT, allowNull: false, comment: "文章内容" }, userId: { type: Sequelize.INTEGER, allowNull: false, comment: "关联用户---此文章是哪个用户发表的" } }) // 创建关联 两种 ,效果一样 推荐两个都写 // // 第一种情况 只能先查blog在找到user Blog.belongsTo(User, {//默认关联id // 创建外键 Blog.userId -> User.id foreignKey: "userId" }) // 第二种情况 只能先查user在找到blog User.hasMany(Blog, { // 创建外键 Blog.userId -> User.id foreignKey: "userId" }) module.exports = { User, Blog }

7.在src文件夹下创建sync.js将建立的数据模型同步到mysql数据库

// 同步到数据库 const seq = require('./seq'); require('./model'); // 测试连接 seq.authenticate().then(() => { console.log('auth ok') }).catch(() => { console.log('auth err') }) // 执行同步 // force: true 如果数据库中存在这个表,就先把它删掉 seq.sync({ force: true }).then(() => { console.log('sync ok'); process.exit(); })

8.在src文件夹下新建create.js文件 插入数据

// 插入数据 const { Blog, User } = require('./model'); !(async function () { // 创建用户 // 创建张三 const zhangsan = await User.create({ userName: 'zhangsan', password: '123', nickName: '张三' }) const zhangsanId = zhangsan.dataValues.id; // insert into users (...) values (...) // 创建李四 const lisi = await User.create({ userName: 'lisi', password: '123', nickName: '李四' }) const lisiId = lisi.dataValues.id; // 创建博客 const blog1 = await Blog.create({ title: "标题1", content: "内容1", userId: zhangsanId }) const blog2 = await Blog.create({ title: "标题2", content: "内容2", userId: zhangsanId }) const blog3 = await Blog.create({ title: "标题3", content: "内容3", userId: lisiId }) const blog4 = await Blog.create({ title: "标题4", content: "内容4", userId: lisiId }) console.log('blog1',blog1.dataValues) console.log('blog2',blog2.dataValues) console.log('blog3',blog3.dataValues) console.log('blog4',blog4.dataValues) })()

9.在src文件夹下创建select.js查询数据库 连表查询

const { Blog, User } = require('./model') !(async function () { // 查询一条记录findOne // const zhangsan = await User.findOne({ // where: { // userName: "zhangsan" // } // }) // console.log('zhangsan', zhangsan.dataValues) // 查询特定的列 attributes // const zhangsanName=await User.findOne({ // attributes:['userName','nickName'], // where:{ // userName:"zhangsan" // } // }) // console.log("zhangsanName",zhangsanName.dataValues) // 查询一个列表 list // 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条 // offset: 0,//跳过多少条 // order: [ // ['id', 'desc'] // ] // }) // console.log('blogPageList', blogPageList.map(blog => blog.dataValues)) // 查询总数 // const blogListAndCount = await Blog.findAndCountAll({ // limit: 2, // offset: 0, // order: [ // ['id', 'desc'] // ] // }) // console.log('blogListAndCount', // blogListAndCount.count,//所有的总数,不考虑分页 // blogListAndCount.rows.map(blog => blog.dataValues)//当前查询的数据 // ) // 连表查询1 // const blogListWithUser = await Blog.findAndCountAll({ // order: [ // ['id', 'desc'] // ], // // 通过userName='zhangsan'查询出blog // include: [ // { // model: User, // attributes: ['userName', 'nickName'], // where: { // userName: 'zhangsan' // } // } // ] // }) // // 因为查询出符合blog的可能又多条数据 // // 而每个blog下面又可能又多条user数据 // 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; // }) // ) })()

10.在src文件夹下创建update.js 更新数据

const { User } = require('./model'); !(async function () { const updateRes = await User.update({ nickName: '张三' }, { where: { userName: 'zhangsan' } }) // 返回结果updateRes... [ 1 ] // 所以当updateRes[0] > 0 证明操作成功 console.log('updateRes...', updateRes[0] > 0) })();

11.在src文件夹下创建delete.js文件 删除数据

const { User, Blog } = require('./model'); !(async function () { // // 删除一条博客 // const delBlogRes = await Blog.destroy({ // where: { // id: 4 // } // }) // // 返回结果 1 删除的条数 // console.log('delBlogRes', delBlogRes > 0) // 删除一个用户 注意 : 外键关联 const delUserRes = await User.destroy({ where: { id: 1 } }) console.log('delUserRes',delUserRes) })();
最新回复(0)