MySQL 연동

jaegeunsong97·2023년 9월 26일
0

Node.js

목록 보기
6/7

데이터베이스

  • DBMS
    • MySQL, Oracle
    • NoSQL기반의 DBMS - MongoDB
  • 데이터베이스 분류
    • RDB
      • 행과 열
      • SQL 통해서만 데이터베이스 접근
    • NoSQL
      • SQL 사용 X 데이터베이스
      • 나머지는 RDB 특성과 동일
      • 확장이 쉽다
        • RDB 확장 어려움 : NoSQL은 데이터 분산 저장 지원하기 때문에 확장 EZ
          • key, value 모델 : object, json 형태로 데이터 쉽게 저장 및 출력 가능
          • document 모델 : collection의 일부
          • graph 모델 : 데이터를 노드형태로 저장, 노드 간의 흐름 또는 관계를 저장
          • column, family 모델 : 한 행마다 각각 다른 수, 다른 종류의 열을 가질 수 있음
      • 다루기 쉽다 : JS object 사용하는 것처럼 데이터 입출력 쉬움
      • 스키마 정의 없이도 사용 가능

스키마와 테이블 생성

  • 표(table) * N -> 스키마(Schema)
  • 스키마(Schema) * N -> 데이터베이스
show databases; // 데이터베이스 목록을 보여줌
use {schema 명}; // 데이터베이스 목록 중 1개를 사용
show tables; // 사용중인 DB의 테이블을 보여줌

// 스키마 생성
create database {schema 명} default character set utf8; // 스키마 생성
use {schema 명}; // 스키마 조작 전 사용 알림
show tables; // Empty 값

// 테이블 생성
create table {테이블 명} (
	-> id int(11) not null auto_increment,
    -> title varchr(100) not null,
    -> content text null
    -> created datetime not null,
    -> writer varchar(100) null,
    -> email varchar(100) null,
    -> primary key(id));
desc {테이블 명}; // 테이블 보기

CRUD

// 데이터 추가
insert into 테이블명 (필드명...) values(입력할 값...); //**
insert into post(title, content, created, writer, email) values('라면', '라면은 역시 밤에 먹는게 꿀맛', now(), 'song', 'song@naver.com');


// 데이터 조회
select 필드명... from 테이블; //**
select * from post;
select id, title, content from post;

select 필드명... from 테이블 where 조건; //**
select * from post where writer = 'song';

select 필드명... from 테이블 order by 필드명 (desc?); //**
select * from post order by id desc;

select 필드명... from 테이블 limit 출력할 데이터 개수; //**
select * from post limit 3;


// 데이터 수정
update 테이블명 set 수정할 필드 = '수정할 내용' where id = 수정할 데이터 id; //**
update post set content = '성격파탄자' where id = 3;
update post set content = '성격파탄자', writer = '상남자' where id = 3;


// 데이터 삭제
delete from 테이블명 where id = 수정할 데이터 id; //**
delete from post where id = 3;

테이블 분리 및 조인

  • 중복된 컬럼이 있는 경우 -> 분리
    • post의 경우 컬럼에 writer에 lee가 중복되어 들어가 있다면?
rename table {기존 테이블명} to {바꾸고 싶은 테이블명}; 기존 테이블 명 바꾸기

// 새로운 테이블 post, profile 작성 -> 데이터 넣기
create table {테이블명} (
	-> id int(11) not null auto_increment,
    -> title varchr(30) not null,
    -> content text null
    -> created datetime not null,
	-> profile_id int(11) default null,
    -> primary key(id));
create table {테이블명} (
	-> id int(11) not null auto_increment,
    -> writer varchar(30) null,
    -> email varchar(100) null,
    -> primary key(id));
insert into ... 


// 테이블 조인
select 필드명 from 테이블1 left join 테이블2 on 테이블1.profile_id = 테이블2.id; // 형태
select * from post 
	left join profile 
    on post.profile_id = profile.id;
select * from post.id, title, content, created, writer, email 
	left join profile 
    on post.profile_id = profile.id;

MySQL + NodeJS 연동

  • 라이브러리 설치

    • server.js가 있는 폴더로 이동 후
    • npm install --save node-mysql
  • 연동 코드, server.js

var mysql = require("mysql"); // mysql 객체 생성
var conn = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "123456",
    database: "myboard",
});

conn.connect(); // 여기서 접속

conn.query("select * from post", function (err, rows, fields) { 
  	// query()를 통해 어떤 요청도 가능
    if (err) throw err;
    console.log(rows); // 레코드 단위의 모든 데이터
});
.
.
.
  • /list 요청 시 데이터 조회, server.js
.
.
.
app.get("/list", function (req, res) {
	conn.query("select * from post", function (err, rows, fields) {
        if (err) throw err;
        console.log(rows);
    });
});
  • 최종 코드
// Node.js - MySQL 연동코드
var mysql = require('mysql');
var conn = mysql.createConnection({
     host: 'localhost',
     user: 'root',
     password: 'abc0701!!',
     database: 'myboard'
});

conn.connect();

//
const express = require('express'); // express 라이브러리 사용해서 express 객체 생성
const app = express(); // express 사용해서 새로운 app 객체 생성, app : 서버 객체라고 생각

app.listen(8080, function(){ // listen : 서버 띄우고 client 객체의 요청 기다림, function() : 서버 구동시 콜백함수
     console.log("포트 8080으로 서버 대기중.......")
});

app.get('/book', function(req, res) {
     res.send('도서 목록 관련 페이지입니다. ');
});

app.get('/', function(req, res) {
     res.sendFile(__dirname + '/index.html'); //__dirname : 현재 디렉토리 
});

app.get('/list', function(req, res) {
     conn.query("select * from post", function(err, rows, fields) {
          if (err) throw err;
          console.log(rows);
     });
});
profile
현재 블로그 : https://jasonsong97.tistory.com/

0개의 댓글