티스토리 뷰

2017/01/09 - [컴퓨터/node.js] - node.js ) 7일차 - Express Framework ' Hello World '

2017/01/05 - [컴퓨터/node.js] - node.js ) 번외 - Express Framework 및 jade

2016/12/21 - [컴퓨터/node.js] - node.js ) 6일차 - 의존성

2016/12/17 - [컴퓨터/node.js] - node.js ) 5일차 - 모듈화

2016/12/17 - [컴퓨터/node.js] - node.js ) 4일차 - 이벤트형 처리

2016/12/16 - [컴퓨터/node.js] - node.js ) 3일차 - 함수 작성

2016/12/16 - [컴퓨터/node.js] - node.js ) 2일차 - 웹서버 구동

2016/12/16 - [컴퓨터/node.js] - node.js ) 1일차 - Hello World !




오늘은 node.js 를 이용해서 view 까지 만든것을 이용하여 DB를 연결하여 보겠다!



우선 7일차에서 index.html 에서 MySQL DB를 select 를 한다.



1. 7일차 폴더 복사


7일차를 그대로 쓰자 복사 ㄱ ㄱ ㄱ ㄱ ㄱ ㄱ ㄱ

[root@localhost node_test]# cp -r node_7 node_8



2. package.json 추가 및 npm install


7일차에서 작성한 패키지에 MySQL을 추가하고, npm install 을 한번더 때린다.


[root@localhost node_8]# vi package.json 


{

  "name": "marlboroyw",

  "version": "1.0.0",

  "dependencies":

  {

    "express": "~4.13.1",

    "ejs": "~2.4.1",

    "mysql":"*"

  }

}


npm install

[root@localhost node_8]# npm install

npm WARN npm npm does not support Node.js v0.10.46

npm WARN npm You should probably upgrade to a newer version of node as we

npm WARN npm can't make any promises that npm will work with this version.

npm WARN npm You can find the latest version at https://nodejs.org/

marlboroyw@1.0.0 /home/yw/node_test/node_8

└─ mysql@2.12.0 

  ── bignumber.js@2.4.0 

  readable-stream@1.1.14 

  │ ── core-util-is@1.0.2 

  │ ── isarray@0.0.1 

  │ └── string_decoder@0.10.31 

  └── sqlstring@2.2.0 


npm WARN marlboroyw@1.0.0 No description

npm WARN marlboroyw@1.0.0 No repository field.

npm WARN marlboroyw@1.0.0 No license field.



3.  MySQL 관련 설정


User와 Password를 설정하고, 데이터베이스와 테이블을 만든다.

예제니까 아래와 같이 테이블 구조를 만들어 보자.

+--------+------------+------+-----+---------+----------------+

| Field  | Type       | Null | Key | Default | Extra          |

+--------+------------+------+-----+---------+----------------+

| seq    | bigint(20) | NO   | PRI | NULL    | auto_increment |

| id     | text       | YES  |     | NULL    |                |

| passwd | text       | YES  |     | NULL    |                |

+--------+------------+------+-----+---------+----------------+

3 rows in set (0.00 sec)


Select 예제이니, 데이터를 두어개만 넣어보자

mysql> insert into node_test(id, passwd) values ('marlboroyw', '12341234');

Query OK, 1 row affected (0.00 sec)


mysql> insert into node_test(id, passwd) values ('youngwoolee', '11223344');

Query OK, 1 row affected (0.00 sec)



4. connection 생성


router/main.js 를 아래와 같이 수정해 주자.


[root@localhost node_8]# vi router/main.js


var mysql = require('mysql');


// MySQL Connection Setting

var connection = mysql.createConnection({

    host:'localhost',

    port:3306,

    user:'marlboroyw',

    password:'testtest',

    database:'youngwooDB'

});


module.exports = function(app)

{

    app.get('/',function(req,res){

        res.render('index.html')

    });

    app.get('/select',function(req,res){

        var query = connection.query('SELECT * FROM node_test', function(err, rows) {

            console.log(rows);

            res.json(rows);

        });

    });

}



7일차의 about 을 지우고 select 요청을 받았을때, node_test 테이블로부터 데이터를 읽어와 단순 json 형태로 반환하는 예제이다. 

이 코드를 함 돌려보자.


[root@localhost node_8]# node server.js 

Express server has started on port 4000







위와 같이 json 이 출력되면 성공이다.


다음차에서는 insert와 update 를 한꺼번에 하는 기염을 토해 보겠다.







공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함