首页 > 数据库技术 > 详细

使用sequelize实现mysql单表的增删改查

时间:2019-11-22 11:36:06      阅读:115      评论:0      收藏:0      [点我收藏+]
  1. 环境搭建
    • mac
    • node v8.2.0
    • mysql v8.0.16;数据库名称:test;表名称:user

技术分享图片

  1. 依赖安装
    • npm init
    • 新建文件app.js
    • npm install --save sequelize
    • npm install --save mysql2
  1. 代码实现app.js    
const Sequelize = require(‘sequelize‘);

const sequelize = new Sequelize(‘test‘,‘root‘,‘123‘,{
    host:‘localhost‘,
    dialect:‘mysql‘,
    dialectOptions: {
        socketPath: ‘/tmp/mysql.sock‘ // 指定套接字文件路径
    }
});
// 测试连接
sequelize.authenticate().then(()=>{
    console.log(‘Connection has been established successfully.‘);
}).catch(err=>{
    console.log(‘Unable to connect to the database:‘,err);
});
// 定义模型
const User = sequelize.define(‘user‘,{
    id:{
        type:Sequelize.NUMBER,
        primaryKey:true
    },
    name:{
        type: Sequelize.STRING
    }
},{
    tableName:‘user‘,
    timestamps: false
})
// 查询
User.findAll().then(users=>{
    console.log(‘All users:‘,JSON.stringify(users,null,4));
})
// 新增
// User.create({id:4,name:‘john‘}).then(res=>{
//     console.log(‘name:‘,res.name)
// })
// 删除
// User.destroy({
//     where:{
//         id:4
//     }
// }).then(()=>{
//     console.log(‘Done‘);
// })
// 更新
// User.update({name:‘张三丰‘},{
//     where: {
//         id:3
//     }
// }).then(()=>{
//     console.log(‘Done‘)
// })

 

  1. 项目运行
    • node app.js

使用sequelize实现mysql单表的增删改查

原文:https://www.cnblogs.com/xingguozhiming/p/11910469.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!