Postgre와 nodejs(Express.js) 연동 - 1 (연결확인 및 .env 설정)
전제조건
postgre가 설치되어 있어야 한다.
express js 모듈을 생성해야한다. (https://datobi.tistory.com/3)
테스트할 테이블이 생성되어 있어야 한다.
나는 heidiSQL을 사용중이고 student라는 간단한 테이블을 생성했다.
CREATE TABLE "student" (
"idx" INTEGER NOT NULL,
"name" VARCHAR NOT NULL,
"age" INTEGER NOT NULL,
"grade" CHAR(1) NOT NULL,
"address" VARCHAR NOT NULL,
PRIMARY KEY ("idx")
);
INSERT INTO "student" VALUES (1, '김똘똘', 10, 'B', '서울시');
INSERT INTO "student" VALUES (2, '이장님', 9, 'A', '서울시');
INSERT INTO "student" VALUES (3, '홍길동', 11, 'C', '강릉시');
INSERT INTO "student" VALUES (4, '윤뽀뽀', 10, 'A', '제주시');
INSERT INTO "student" VALUES (5, '박박', 9, 'D', '경기도');
대략 이런 모습이다. 이제 연동을 해보자.
Step1. pg 모듈 설치
npm i pg --save
위 명령어를 통해 pg 모듈을 설치한다.
Step2. 연결 확인
db 라는 폴더를 만들고 config.js 라는 파일을 만들었다.
const { Pool } = require('pg')
const pool = new Pool(
{
host: 'localhost',
user: 'postgres',
password: '1234',
port: 5432,
database: 'TEST'
}
)
pool.query('SELECT * from student', (err, res) => {
console.log(err, res)
pool.end()
})
위 코드는 db.js 이다. postgre는 Client와 Pool 두가지가 있는데 (사용하는데에 별 차이는 없다)
보통은 pool을 사용하길 권장한다.
그 이유는 여러 동시 요청들이 있을 경우 Pool을 사용하는 것이 낫기 때문이다.
참고
How can I choose between Client or Pool for node-postgres
From https://node-postgres.com/features/connecting , seems like we can choose between Pool or Client to perform query pool.query('SELECT NOW()', (err, res) => { console.log(err, res) pool.e...
stackoverflow.com
https://node-postgres.com/features/pooling
Pooling
If you're working on a web application or other software which makes frequent queries you'll want to use a connection pool. The easiest and by far most common way to use node-postgres is through a connection pool. Why? Connecting a new client to the Postgr
node-postgres.com
heidiSql 세션 관리자를 보면 연결 정보들이 나와있다.
host : 호스트명 / IP (127.0.0.1 이나 localhost를 작성)
user : 사용자 (postgres)
password : 암호 (1234)
port : 포트 (5432)
database : 데이터베이스(TEST) - DB가 없을경우 만들어줘야한다.
연결정보를 작성한 뒤, pool.query를 작성한다.
나는 SELECT * from student 이 쿼리를 요청할 것이다.
routes/index.js
var express = require('express');
var router = express.Router();
let db = require('../db/config')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
let db = require('../db/config') 라고 선언을 해주고 난 뒤, npm start 명령어를 콘솔창에 입력하면
db정보를 잘 가져옴을 볼 수 있다.
.env 처리
보통 이렇게 직접적으로 db 정보들을 작성하지 않고 .env를 이용한다.
.env와 관련된 사항들은 이전 포스팅을 참고하자. (https://datobi.tistory.com/21)
db.js
const { Pool } = require('pg')
const pool = new Pool(
{
host: process.env.POSTGRE_HOST,
user: process.env.POSTGRE_USER,
password: process.env.POSTGRE_PW,
port: process.env.POSTGRE_PORT,
database: process.env.POSTGRE_DB
}
)
pool.query('SELECT * from student', (err, res) => {
console.log(err, res)
pool.end()
})
.env
POSTGRE_HOST=localhost
POSTGRE_USER=postgres
POSTGRE_PW=1234
POSTGRE_PORT=5432
POSTGRE_DB=TEST
.env처리를 해주었다.
결과가 동일하게 나옴을 확인 할 수 있다.
참조
Welcome
node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, streaming results, C/C++ bindings, rich type parsing, and
node-postgres.com
관련 소스
https://github.com/datoybi/blog-posting/tree/main/postgre-connect1
GitHub - datoybi/blog-posting: code examples posted on my blog
code examples posted on my blog. Contribute to datoybi/blog-posting development by creating an account on GitHub.
github.com