使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM