카테고리 없음

0728 MySQL

hyerin1201 2023. 7. 28. 19:31

별도의 공간에 data를 담아 놓을 수 있는..시스템 : DataBase (DB)

DB를 효율적으로 관리 할 수 있는 관리체계 :  DBMS (Data Base Management System) 

그 중 가장 대중적인 관리 체계 : MySQL

Node <-> MySQL

 

테이블을 만들어서 데이터 저장하는 방법

1. 명령프롬프트

2. 워크벤치 데이터 테이블 편집


명령프롬프트로 데이터 저장하는 테이블 만들기

 

>명령 프롬프트

CREATE SCHEMA `nodejs` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;

(터미널에 Query ok, ~~ 가 나오면 정상적으로 테이블을 만들 준비가 되었다.)

 

>명령 프롬프트

CREATE TABLE nodejs.users (
    -> id INT NOT NULL AUTO_INCREMENT,
    -> name VARCHAR(20) NOT NULL ,
    -> age INT UNSIGNED NOT NULL,
    -> married TINYINT NOT NULL,
    -> comment TEXT NULL,
    -> created_at DATETIME NOT NULL DEFAULT now(),
    -> PRIMARY KEY(id),
    -> UNIQUE INDEX name_UNIQUE (name ASC))
    -> COMMENT = "사용자 정보"
    -> ENGINE = InnoDB;

(테이블 한개가 완성됨)

 

>명령프롬프트

use nodejs;

DESC users;

입력하면 작성한 테이블을 볼 수 있다.


테이블 한개 더 만들어보기

>명령 프롬프트

CREATE TABLE nodejs.comments (
    -> id INT NOT NULL AUTO_INCREMENT,
    -> conmmenter INT NOT NULL ,
    -> conmment VARCHAR(100) NOT NULL ,
    -> created_at DATETIME NOT NULL DEFAULT now(),
    -> PRIMARY KEY(id),
    -> INDEX commenter_idx (commenter ASC),

    -> CONSTRAINT commenter,

    -> FOREIGN KEY (commenter)

    -> REFERENCES nodejs.users(id)

    -> ON DELETE CASCADE

    -> ON UPDATE CASCADE)
    -> COMMENT = "댓글"
    -> ENGINE = InnoDB;

(테이블 한개가 완성됨)

 

>명령 프롬프트

DESC comments;

입력하면 작성한 해당 테이블을 볼 수 있다.

 

>명령 프롬프트

SHOW TABLES;

모든 테이블을 보여준다.


데이터값 넣기 (C / R / U / D)

> INSERT INTO nodejs.users(name, age, married, comment) VALUES ("kim", 20, 0, "자기소개2");

 

입력한 데이터 확인하기 (C / R / U / D)

> SELECT * FROM nodejs.users;

 

> INSERT INTO nodejs.comments (commenter, comment) VALUES (1, "안녕하세요 kim의 댓글입니다.");

> SELECT * FROM nodejs.comments;

 

데이터 수정 (C / R / U / D)

> UPDATE nodejs.users SET comment = "바꿀내용" WHERE id = 1;

> SELECT * FROM nodejs.users;

 

데이터 삭제 (C/ R / U / D)

> DELETE FROM nodejs.users WHERE id = 1;

(users 테이블의 id 1값의 해당 행 데이터를 모두 삭제한다.)

 

CRUD

Create 컴포넌드

Read 출력에팔요한 소스코드 및 저장공간

Update 변경 추가 저장공간

Delete 삭제처리 코드 이벤트

대부분의 컴퓨터 소프트웨어 및 프로그램들이 가지고 있는 기본적인 데이터 처리기능을 4개의 섹션으로 요약해놓은 개념


* mysql 데이터와 node.js를 연결하기

데이터를 html 방식으로 전달해야함. :  nunjucks

node 와 mysql 연동 (중간다리역할) : sequelize

데이터를 자바스크립트 언어로 가져오기 : sequelize-cli 

node 와 mysql 연결 허브:  mysql2 

노드로 활용된 업데이트 데이터 확인가능:  nodemon

 

터미널 파워셀 에서 설치하기.

> npm init -y

> npm i express morgan nunjucks  sequelize sequelize-cli mysql2 

> npm i nodemon

 

시퀄라이즈 초기화

> npx sequelize init (*초기화) ---> config, models, 생성 (config : node가 mysql에 저장된db를 가져오게 해주는 관문 역할 / models : 

*config.json : password 입력, database : 파일이름 입력

 

mysql - node 연동

*models -> index.js : 

const Sequelize = require("sequelize");
const User = require("./user");
const Comment = require("./comments");

const env = process.env.NODE_ENV || "development";
const config = require("../config/config")[env];
const db = {};

const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  config
);

db.sequelize = sequelize;
 
db.sequelize = sequelize;

db.User = User;
db.Comment = Comment;

User.initiate(sequelize);
Comment.initiate(sequelize);

User.associate(db);
Comment.associate(db);

module.exports = db;

 

express 로 서버구현 하기 및 데이터 

*app.js

const express = require("express");
const path = require("path");
const morgan = require("morgan");
const nunjucks = require("nunjucks");

const { sequelize } = require("./models");

const app = express();
app.set("port", process.env.PORT || 3001);
app.set("view engine", "html");
nunjucks.configure("views", {
  express: app,
  watch: true,
});
sequelize
  .sync({ force: false })
  .then(() => {
    console.log("데이터베이스 연결 성공");
  })
  .catch((err) => {
    console.error(err);
  });

app.use(morgan("dev"));
app.use(express.static(path.join(__dirname, "public")));
//localhost:3001/public/index.js
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use((req, res, next) => {
  const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
  error.status = 404;
  next(error);
});

app.use((err, req, res, next) => {
  res.locals.message = err.message;
  res.locals.error = process.env.NODE_ENV !== "production" ? err : {};
  res.status(err.status || 500);
  res.render("error");
});

app.listen(app.get("port"), () => {
  console.log(app.get("port"), "번 포트에서 대기중");
});

 

*models -> user.js : 모델 템플릿 만들기

const Sequelize = require("sequelize");

class User extends Sequelize.Model {
  static initiate(sequelize) {
    User.init(
      {
        name: {
          type: Sequelize.STRING(20),
          allowNull: false,
          unique: true,
        },
        age: {
          type: Sequelize.INTEGER.UNSIGNED,
          allowNull: false,
        },
        married: {
          type: Sequelize.BOOLEAN,
          allowNull: false,
        },
        comment: {
          type: Sequelize.TEXT,
          allowNull: true,
        },
        created_at: {
          type: Sequelize.DATE,
          allowNull: false,
          defaultValue: Sequelize.NOW,
        },
      },
      {
        sequelize,
        timestamps: false,
        modelName: "User",
        tableName: "users",
        paranoid: false,
        charset: "utf8",
        collate: "utf8_general_ci",
      }
    );
  }
  static associate(db) {}
}

module.exports = User;

*models -> comment.js : 모델 템플릿 만들기

const Sequelize = require("sequelize");

class Comment extends Sequelize.Model {
  static initiate(sequelize) {
    Comment.init(
      {
        comment: {
          type: Sequelize.STRING(100),
          allowNull: false,
        },
        created_at: {
          type: Sequelize.DATE,
          allowNull: true,
          defaultValue: Sequelize.NOW,
        },
      },
      {
        sequelize,
        timestamps: false,
        modelName: "Comment",
        tableName: "comments",
        paranoid: false,
        charset: "utf8",
        collate: "utf8_general_ci",
      }
    );
  }
  static associate(db) {}
}

module.exports = Comment;

 

> 파워쉘

>npm run start

 


공부한 내용

데이터베이스 정리

데이터베이스 관리해주는 시스템 > MySQL

CRUD

MySQL 콘솔창 / 워크벤치 활용

Sequelize 서버에 저장된 데이터 - MySQL로 전달하기 위한 중간 맵핑 역할 

express 활용 서버 구현


vsCode 에서 mysql 실행하기

1. vsCode -> cmd터미널 -> cd [mysql이 설치되어 있는 경로 입력 ]

( 나같은 경우는 cd C:\Program Files\MySQL\MySQL Server 8.0\bin)

 

2.터미널에  mysql -h localhost -u root -p 입력

3. 비밀번호를 입력하라고 나온다. 비밀번호 입력하면 끝


 

mysql 오류

ERROR 1045 (28000) : Access denied for user 'root'@'localhost' (using password: YES) 

mysql > exit 로 나오지 않고 강제로 종료했을때 발생하는 오류이다.

 

 

해결방법!

작업관리자에서 mysqld.exe를 작업끝내기로 종료한다.

 

윈도우-찾기-서비스

서비스 들어가서 mysql을 찾아 시작을 눌러준다.

 

순서를 꼭 지킬것!

다시 vscode로 돌아가 실행하면 정상적으로 실행된다.