스터디📖/Node.js

[nodejs 강좌] Node.js 로 Database 다루기 소개와 웹애플리케이션 만들기 - 섹션 2. MySQL 을 NodeJS 로 제어 방법

호프 2022. 2. 8. 18:51

MySQL 1 : 소개

3대 관계형 데이터베이스 중 하나.

웹의 발전과 함께 부상함.

AMP ( Apache + MySQL, PHP )

MySQL과 호환되는 MariaDB, Aurora


MySQL 3.1 : 구조

MySQL 설치는 이미 되어 있기 때문에 설치 부분은 넘겼다. MySLQ이 설치되어 있는지를 확인하려면

mysql -uroot -p

를 입력한 후, root 비밀번호를 입력해서 mysql 서버에 접속이 되는지 확인하면 된다.

MySQL의 기본적인 단위는 table

row == 행 == record

column == 열 == attribute

같은 application에서 사용되는 table들의 묶음 == database


MySQL 4 : MySQL 사용하기, MySQL 5 : UPDATE & DELETE

cmd 창에서 sql 문법을 이용해서 데터를 INSERT, SELCT, UPDATE, DELETE하는 방법을 알려준다.

이미 알고 있는 부분이기에 빠르게 넘겼다.


MySQL 6 : node-mysql 1 : 접속

node-mysql 설치

npm install --save node-mysql 을 통해 다운받으라고 했는데.. 공식 문서를 가보니

https://github.com/mysqljs/mysql

따로 설치를 하지 않아도 되는 것 같다..?🤔 일단 설치를 진행하고 따라가보았다. 다행히 예제는 동일하다.

var mysql      = require('mysql');
var conn = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'o2'
}); // 실제 프로젝트를 진행할 때 중요한 정보는 따로 파일을 만들어 공유되지 않도록 관리해야 한다.

conn.connect(); // DB에 연결

var sql = 'SELECt * FROM topic';
conn.query(sql, function(err, rows, fields){ // 쿼리를 날리는 함수. 
    if(err){
        console.log(err);
    } else {
        console.log('rows', rows); // 열 반환
        console.log('fileds', fields); // fields 반환 - 보통 column을 뜻함.
    }
})
conn.end(); // close connection

이렇게 하면

rows [
  RowDataPacket {
    id: 1,
    title: 'JavaScript',
    description: 'Computer language for web.',
    author: 'egoing'
  },
  RowDataPacket {
    id: 2,
    title: 'npm',
    description: 'node package manager',      
    author: 'leezche'
  }
]
fileds [
  FieldPacket {
    catalog: 'def',
    db: 'o2',
    table: 'topic',
    orgTable: 'topic',
    name: 'id',
    orgName: 'id',
    charsetNr: 63,
    length: 11,
    type: 3,
    flags: 16899,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'o2',
    table: 'topic',
    orgTable: 'topic',
    name: 'title',
    orgName: 'title',
    charsetNr: 33,
    length: 300,
    type: 253,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'o2',
    table: 'topic',
    orgTable: 'topic',
    name: 'description',
    orgName: 'description',
    charsetNr: 33,
    length: 196605,
    type: 252,
    flags: 4113,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  },
  FieldPacket {
    catalog: 'def',
    db: 'o2',
    table: 'topic',
    orgTable: 'topic',
    name: 'author',
    orgName: 'author',
    charsetNr: 33,
    length: 90,
    type: 253,
    flags: 4097,
    decimals: 0,
    default: undefined,
    zeroFill: false,
    protocol41: true
  }
]

위와 같이 출력되는 걸 확인할 수 있다. 그나저나 저 fields 값은 뭘까..


MySQL 7 : node-mysql2 : SELECT&INSERT

INSERT

var sql = 'INSERT INTO topic (title, description, author) VALUES (?, ?, ?)'; // ? == 치환자
var params = ['Supervisor', 'Watcher', 'author'];
conn.query(sql, params, function(err, rows, fields){
    if(err){
        console.log(err);
    } else{
        console.log(rows.insertId); // insertId를 얻어올 수 있음.
    }
})

MySQL 8 : node-mysql 3 : UPDATE & DELETE

UPDATE

var sql = 'UPDATE topic SET title=?, author=? WHERE id=?'; // ? == 치환자
var params = ['hadestown', 'Hermes', '3'];
conn.query(sql, params, function(err, rows, fields){
    if(err){
        console.log(err);
    } else{
        console.log(rows);
    }
})

DELETE

var sql = 'DELETE FROM topic WHERE id=?'; // ? == 치환자
var params = [3];
conn.query(sql, params, function(err, rows, fields){
    if(err){
        console.log(err);
    } else{
        console.log(rows);
    }
})