SQL

SQL 초급 - MySQL 기반 웹사이트 만들기 01 (설치/기본뼈대)

H-V 2021. 10. 1. 19:50

인프런 '갖고노는 MySQL 데이터베이스 by 얄코' 참조 

 

 

 

01 MySQL 활용하여 웹사이트 만들기

 

 

1) 프로젝트 생성

  • 원하는 경로에 아래와 같이 폴더를 생성 후 VS Code에서 열기

 

 

2) 필요 프로그램 깔기

  • Ctrl + `로 터미널 열기 및 다음 코드 실행 (설치 오류이면 node.js 설치 확인 및 VScode 재실행하면 됨)
npm install -g express-generator

 

  • 아래 버튼을 눌러 cmd로 바꾼 후 코드 입력

express --view=hbs .

npm install - 필요 기능을 node_modeules에 담아 모두 다운로드 해줌 

npm install -g nodemon - 새로운 저장목록들을 자동으로 웹사이트에 올려줌

굿!

 

 

  • 아래 코드 추가
"start-w": "nodemon ./bin/www"

  • 프로젝트 실행 명령어 삽입 
npm run-script start-w

접속 가능하다!

 

 

3) 프로젝트 기본 뼈대

  1. index.js → 경로를 가지고 있고 여기서 가지고 있는 특정 부분을 컨토를 할 수 있다 ({title:'Express'})
  2. .hbs → STS의 같은 개념으로 .jsp가 있다. 템플릿 엔진의 하나
  3. index.hbs → index.js 에서 적힌 내용이 반영 된다
  4. layout.hbs → .hmtl처럼 외부 내용을 컨트롤 할 수 있다.
  5. app.js → 뷰 엔진 선택 등의 세팅이 잡혀있는 파일로 건들지 않는다. 
  6. MySQL용 파일이 추가 될 예정 

  • index.js 에서 입력값이 index.hbs로 가서 반영이 된다. layout.hbs는 html과 같은 형태로 외부적인 부분을 컨트롤 하는 부분 
  • 예로 
    타이틀을 'Yo!'로 바뀌면 타고 타고 타고 아래처럼 바뀐다

 

 

 

 

04) 기본 사이트 구성

*외부 구성

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel='stylesheet' href='/stylesheets/style.css' />
  <title>{{title}}</title>
</head>
<body>
  {{{body}}}
</body>
</html>
*public → stylesheets → style.css

🔗 /public/stylesheets/style.css 링크 클릭 후 복붙
* sections.hbs #섹션 페이지 구성

<h1>{{ title }}</h1>

<ul>
  <li>
    <a href="biz-simple?section=">
      <span>🌎</span> 전체
    </a>
  </li>
  {{#each sections}}
    <li>
      <a href="biz-simple?section={{ section_id }}">
        <span>{{ icon }}</span>
        {{ section_name }}
      </a>
    </li>
  {{/each}}
</ul>
*index.js 내용을 아래로 수정하면 localhost:3000 경로는 sections.hbs로 바뀜

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('sections', { 
    title: '섹션 목록' 
  });
});

module.exports = router;

→ 하지만 아직 sections.hbs 아래부분이 나오지 않는다. 이부분을 이제 MySQL로 채워서 뿌릴 예정

 

 

 

05) MySQL2 모듈 설치

npm install --save mysql2
  • 설치 후 package.json으로 가서 ""start-w""nodemon ./bin/www" 를 재실행\
  • /database/sql.js 만든 후 복붙
const mysql = require('mysql2');

const pool = mysql.createPool(
  process.env.JAWSDB_URL ?? {
    host: 'localhost',
    user: 'root',
    port: '3307',
    database: 'mydatabase',
    password: '12345678',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  }
);
const promisePool = pool.promise();

const sql = {

  getSections : async () => {
    const [rows] = await promisePool.query(`
      SELECT * FROM sections
    `)
    return rows
  },

}

module.exports = sql
  • 기본적인 VS Code를 MySQL과 연결하는 코드이며 'const sql' 함수가 MySQL에서 'SELECT * FROM sections' 쿼리를 실행하여 결과를 'rows'에 담고 리턴하는 형식
  • 혹여나 하나 이상의 DB를 사용중이라면 포트번호 꼭 확인해서 저렇게 넣어줘야 한다!!

 

  • 이제 이 내용을 우리 사이트에 연결을 해야 한다 (index.js)
var express = require('express');
var router = express.Router();

var sql = require('../database/sql')

const sectionIcons = [
  '🍚', '🍿', '🍜', '🍣', '🥩', '☕', '🍰'
]

router.get('/', async function(req, res, next) {

  const sections = await sql.getSections()
  sections.map((item) => {
    item.icon = sectionIcons[item.section_id - 1]
  })

  res.render('sections', { 
    title: '섹션 목록',
    sections
  });
});

module.exports = router;

굿!