본문 바로가기

React

Mysql2 Sequelize 기본 세팅

 

 

Mysql2 Sequelize 기본 세팅하는 법에 대해 알아보자

 

세팅하기 전에 먼저 npm을 이용해서 mysql2 와 sequelize를 설치하도록 하자

 

npm install mysql2 sequelize

 

 

아래의 코드는 sequelize의 기본 세팅 구조이다.

const {Sequelize, DataTypes} = require('sequelize')

// 인자값이 4개가 있다.
// 1. 데이터베이스명 create database ~
// 2. 데이터베이스 계정명 -> ####
// 3. password -> ####
// 4. Object
//   4.1 host:localhost
//   4.2 dialect:'mysql'

const seqeulize = new Sequelize('example','####','####',{
    host:'localhost',
    dialect:'mysql'
})

// seqeulize.sync().then(data=>{
//     console.log('접속됨')
// })
// .catch(error => {
//     console.log('접속실패함')
// })

async function init() {
    try {
        comment()
        await seqeulize.sync({force:true}) //  force:true -> 실행할때마다 내가 만든 것을 수정시킨다
        console.log('접속')
        insert()
        // 코드 작성하면 sequelize 코드를 다 실행할 수 있다.
    } catch (e) {
        console.log('접속안됨')
    }
}

init()

function comment(){
    const Comment = seqeulize.define('Jang',
    {
        // 필드내용이 들어감
        subject:{
            type:DataTypes.STRING(30),
            allowNull:false,

        },
        content:{
            type:DataTypes.STRING(50),
            allowNull:false,
        }
    },
    {
        // 옵션내용이 들어감
        
        timestamps:false
    })

    return Comment
}

const insert = async () => {
    const Comment = comment()
    Comment.create({subject:'asdads',content:'adasdadsadsa'})
}