본문 바로가기
  • Let's go grab a data
Development/NodeJS

postgresql 설치, db, table 생성, pg-promise로 연결, counter구현

by pub-lican-ai 2017. 2. 3.
반응형

postgresql 설치, db, table 생성, pg-promise로 연결, counter구현  #postgresql #pg-promise #nodejs #simple counter #bluebird


[postgreSQL 설치]

1. 시스템에 맞게 다운로드 (9.6.1 / Windows x86-64)

https://www.enterprisedb.com/downloads/postgres-postgresql-downloads#windows


2. 다운 받은 설치파일을 실행하여 설치


3. 설치 폴더 설정(default) - 데이터 디렉토리 설정(default) - password (superuser: postgres/password: root로 설정) - Port (default: 5432) - Locale (Korean, Korea로 설정) - Install

   - Stack Builder 실행여부: 체크 해제 후 Finish


[postgresql 외부 접속 허용] -optional

1. pg_hba.conf 파일 열어 #IPv4 local connections: 에 하단의 항목을 추가하고 저장

  host all all 192.168.1.0/24 md5


[pgAdmin DB, Table 생성]

1. 윈도우 시작 - 모든 프로그램 - Postgresql 9.6.1폴더 내 pgAdmin 실행


2. 좌측 브라우저의 Servers내에 PostgreSQL 9.6.1 의 + 버튼을 열어 비밀번호(root)로 들어감 (Save Password) 

   - Server Connected라는 메시지가 나오면서 Dashboard에 데이터가 나오면 연결된 상태


3. Databases 우클릭 - Create - Database... 클릭 - Database이름에 myData넣고 Save


4. 생성된 'myData' database의 + 버튼을 눌러 연결함 - Schemas - public - Tables 우클릭 - Create - Table 클릭 - general 탭의 테이블 명에 counter 입력 - Columns 탭의 오른쪽 + 버튼을 누르고

 - 생성된 column의 Name에 'count', Data type에 'integer' 넣고 Save


5. 생성된 'counter'테이블 우클릭 - Query Tool 클릭 - INSERT into counter values (0); 입력하고 F5로 실행 - 아래와 같이 나오면 Insert 성공 - counter 테이블 우클릭 - View Data로 확인

  INSERT 0 1

  Query returned successfully in 122 msec. 



[pg-promise로 연결]

1. 프로젝트 폴더에서 cmd나 git bash를 열어 pg-promise와 bluebird를 설치

 $npm install pg-promise --save

 https://www.npmjs.com/package/pg-promise

 $npm install bluebird --save

http://bluebirdjs.com/docs/getting-started.html


2. 프로젝트 폴더내 node_modules에서 설치 확인


3. 프로젝트 폴더 내 view 폴더 우클릭 - New File - 'testejs1.ejs' 이름으로 생성 - 아래와 같이 내용 추가

http://pubdata.tistory.com/84 내용 참고하여 ejs파일 생성

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title>Test EJS page</title>

  </head>

  <body>

    <h2>Hello ejs</h2>

    <br>

    view counter from postgres db: <%= count %>

  </body>

</html>


4. 프로젝트 폴더에 우클릭 - New File - queries.js 파일 생성 - 아래와 같이 내용 추가

var promise = require('bluebird');

var options = {

  promiseLib: promise

};

var pgp = require('pg-promise')(options);

var connectionString = 'postgres://postgres:root@localhost:5432/myData';

//이곳에 위 설치할때 설정 및 생성한 User/PW/Port/DB name을 넣음

var db = pgp(connectionString);


module.exports = {

  addCount: addCount

};


function addCount(req, res, next) {

  db.any('select count from counter1')

    .then(function (data) {

    var currentcount = {count:data[0].count};

    currentcount.count++;

    db.none('update counter set count=$1',[currentcount.count])

      .then(function (data) {        

        res.render('testejs1',currentcount);

      })

      .catch(function (err) {

        return next(err);

      });

    })

    .catch(function (err) {

      return next(err);

    });

}


5. app.js(index.js)에서 아래와 같이 내용 추가

var express = require('express');

var db = require('./queries');

app.get('/pg/count', db.addCount);


6. nodemon으로 실행시키고 http://localhost:3001/pg/count 호출하여 count가 증가하는지 확인



반응형