zoukankan      html  css  js  c++  java
  • 使用sequelize实现mysql单表的增删改查

    1. 环境搭建
      • mac
      • node v8.2.0
      • mysql v8.0.16;数据库名称:test;表名称:user

    11_06_06__07_01_2019.jpg

    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
  • 相关阅读:
    队列
    集合
    运算符
    数组
    项目研发常用的优化策略——遮挡剔除(Occlusion Culling)
    Unity专题_简单的寻路导航
    Unity重要脚本函数
    Unity输入管理器
    Unity脚本的生命周期
    接口
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/11910469.html
Copyright © 2011-2022 走看看