DB 연동하기

DB 연동하기

1. DB 연동하기

 - Express.jssql데이터베이스를 연동해봅시다.

 - #1. SQLyog에 들어가서 먼저 다음과 같이 입력하여, 데이터베이스를 생성합니다.

    ※ SQL에 관한 공부는 여기로!

CREATE DATABASE wise_saying;
USE wise_saying;

 

 - #2. wise_saying라는 테이블을 생성하고 show tables를 입력하여 제대로 생성 되었는지 확인해봅시다.

CREATE TABLE wise_saying (
    id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
    regDate DATETIME NOT NULL,
    content VARCHAR(200) NOT NULL,
    author VARCHAR(50) NOT NULL
);

SHOW TABLES;

 

 - #3. 생성되었는지 확인이 되었다면, 다음과 같이 입력하여 데이터를 추가합니다.

INSERT INTO wise_saying
SET regDate = NOW(),
content = '나는 의적이다.',
author = '홍길동';

INSERT INTO wise_saying
SET regDate = NOW(),
content = '나는 도적이다.',
author = '임꺽정';

INSERT INTO wise_saying
SET regDate = NOW(),
content = '나는 사또다.',
author = '변학도';

 

 - #4. 데이터 추가 후, 다음과 같이 입력하여 제대로 추가되었는지 확인해봅시다.

SELECT * FROM wise_saying;

 

    ※ DB 입력한 것을 남겨두기 위해 db.sql이라는 파일을 생성 후, 지금까지 입력한 것을 붙여넣어 줍니다.

 

 - #5. 이제 Node.jsMySQL 데이터베이스 상호작용하기 위해 터미널에 npm i mysql2 라고 입력합니다.

    → 설치되었다면, package.json mysql2가 추가된 것을 확인할 수 있습니다.

 

 - #6. 설치가 끝났다면, app.js에 다음과 같이 입력하여 DB를 연동해줍니다.

import express from "express";
import mysql from "mysql2/promise";

// DB 설정
const pool = mysql.createPool({
  host: "localhost",
  user: "newbean",
  password: "juv0312",
  database: "wise_saying",
  waitForConnections: true, // 연결하는 동안 대기 여부
  connectionLimit: 10, // 연결 제한 개수
  queueLimit: 0, // 최대 0(제한없음)개의 연결 요청을 대기열에 추가
});

const app = express();
const port = 3000;

const wiseSayings = [
  {
    content: "나는 의적이다.",
    author: "홍길동",
  },
  {
    content: "나는 도적이다.",
    author: "임꺽정",
  },
];

app.get("/wise-sayings", async (req, res) => {
  // 쿼리를 가져옴
  const [rows] = await pool.query("SELECT * FROM wise_saying ORDER BY id DESC");

  // json으로 담음
  res.json(rows);
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

 

 - 브라우저로 localhost:3000/wise-sayings를 입력해보면 다음과 같이 출력됩니다!

 

 - #7. 데이터를 하나만 받고 싶을 경우, 코드 중 app.get(...) 아래 줄에 다음과 같이 입력해줍니다.

// 데이터를 원하는 id만 받아오기
app.get("/wise-sayings/:id", async (req, res) => {
  // 요청을 보냄
  const { id } = req.params;
  const [rows] = await pool.query("SELECT * FROM wise_saying WHERE id = ?", [
    id,
  ]);

  // json으로 담음
  res.json(rows[0]);
});

 

 - #8. 브라우저에 localhost:3000/wise-sayings/3을 입력해봅시다.

    → id가 3인 데이터가 출력되었습니다!

 

 

 - 이렇게 하면 sql로 작성한 db를 연동하여, express.js로 브라우저에 데이터를 출력할 수 있습니다.

 

++ 없는 id를 요청하는 경우, 원래 코드에 다음과 같이 추가합니다.

    → 이렇게 하면, 없는 id를 요청 시, not found라고 출력이 됩니다.

// 데이터를 원하는 id만 받아오기
app.get("/wise-sayings/:id", async (req, res) => {
  // 요청을 보냄
  const { id } = req.params;
  const [rows] = await pool.query("SELECT * FROM wise_saying WHERE id = ?", [
    id,
  ]);

  // 없는 id를 요청하는 경우
  if (rows.length == 0) {
    res.status(404).send("not found");
    return;
  }

  // json으로 담음
  res.json(rows[0]);
});

 

 

    ※ 전체 코드

import express from "express";
import mysql from "mysql2/promise";

// DB 설정
const pool = mysql.createPool({
  host: "localhost",
  user: "newbean",
  password: "juv0312",
  database: "wise_saying",
  waitForConnections: true, // 연결하는 동안 대기 여부
  connectionLimit: 10, // 연결 제한 개수
  queueLimit: 0, // 최대 0(제한없음)개의 연결 요청을 대기열에 추가
});

const app = express();
const port = 3000;

const wiseSayings = [
  {
    content: "나는 의적이다.",
    author: "홍길동",
  },
  {
    content: "나는 도적이다.",
    author: "임꺽정",
  },
];

app.get("/wise-sayings", async (req, res) => {
  // 쿼리를 가져옴
  const [rows] = await pool.query("SELECT * FROM wise_saying ORDER BY id DESC");

  // json으로 담음
  res.json(rows);
});

// 데이터를 원하는 id만 받아오기
app.get("/wise-sayings/:id", async (req, res) => {
  // 요청을 보냄
  const { id } = req.params;
  const [rows] = await pool.query("SELECT * FROM wise_saying WHERE id = ?", [
    id,
  ]);

  // 없는 id를 요청하는 경우
  if (rows.length == 0) {
    res.status(404).send("not found");
    return;
  }

  // json으로 담음
  res.json(rows[0]);
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

'Back-End Study > Express' 카테고리의 다른 글

Express로 todo 리스트 만들기 2  (0) 2024.03.02
Express로 todo 리스트 만들기 1  (0) 2024.03.01
Express로 JSON 응답 받기  (2) 2023.11.22
Express.js 설치  (0) 2023.11.22
Express.js  (0) 2023.11.22