[Node.js] Node.js와 MySQL을 이용한 CRUD 서버 만들기
본문 바로가기
BackEnd/Node.js

[Node.js] Node.js와 MySQL을 이용한 CRUD 서버 만들기

by liveloper jay 2021. 12. 10.

Node.js express 프레임워크와 MySQL을 이용하여 간단한 CRUD API 작성을 진행해보겠습니다. 위의 과정을 위해 먼저 MySQL 모듈 설치 및 서버와의 연동을 먼저 진행해보겠습니다.

 

1. MySQL 설치 및 Node.js 연동

먼저 MySQL 모듈을 설치해 줍니다.

# MySQL을 위한 directory
mkdir mysqdb 
cd mysqdb

npm init
# mysql 모듈 설치
npm install mysql

 

 

MySQL 설치가 완료되었으면 아래와 같이 Node.js 서버를 통해 데이터를 이용할 수 있도록 연결 코드를 작성해줍니다. 이때 createConnection에는 연결할 데이터베이스의 정보를 입력해야 합니다. 각 내용은 다음과 같습니다.

  1. host : 연결할 hostIP 주소

  2. user : DB 사용자의 이름

  3. password : 사용자의 패스워드

  4. database : 사용할 DB의 이름

 

아래 코드는 해당 내용을 참고하여 DB 연결 및 DB가 잘 연결 되었는지 데이터를 조회하는 코드입니다.

const mysql = require("mysql");
const connection = mysql.createConnection({ 
	 host : {host_IP},
	 user : {user_id},
	 password : {Password}, 
	 database : {Database_Name} 
	 }); 
connection.connect();

connection.query('SELECT * from {table}', (error, rows, fields) => {
  if (error) throw error;
  console.log('User info is: ', rows);
});

connection.end();

 

 

 

2. 글 조회/생성/수정/삭제 (CRUD) 기능 구현

 데이터베이스가 정상적으로 연결되었으면 데이터의 조회/ 생성/ 수정/ 삭제 기능을 알아보겠습니다.

 

먼저 데이터의 조회를 위해서는 get 메서드를 통해 조회할 수 있으며, MySQL의 select 쿼리문을 이용하여 데이터를 선택합니다. 아래 예시는 전체 데이터를 조회하는 코드입니다.

// 전체 데이터 조회
router.get('/post', (req, res) => {
	connection.query("SELECT * FROM data", function(err, rows, fields){
		if(err) console.log(err);
    	console.log(rows); 
    	}) 
});

. 여기서 만약 전체 데이터가 아닌 특정 id 값의 데이터만을 조회하고자 하는 경우에는 다음과 같이 조회하고자 하는 경로의 파라미터 값을 받아와서 사용하면 됩니다.

// 특정 id 값 조회
router.get('/post/:id', (req, res) => {
	const param = req.params.id
	connection.query("SELECT * FROM data WHERE id= ?", param, function(err, rows, fields){
		if(err) console.log(err);
    	console.log(rows); 
    	}) 
});

 

 

 데이터의 생성은 post 메서드를 이용하여 할 수 있으며, MySQL의 Insert 쿼리문을 이용하여 데이터를 삽입하는 방식으로 진행하였습니다. 

// 데이터 생성 예제
router.post('/post', (req, res) => {
	connection.query("INSERT INTO User VALUES (...);", function(err, rows, fields){
		if(err) console.log(err);
		console.log(rows);
	})
});

 

 현재 존재하는 데이터의 수정이 필요할 경우 put 또는 patch 메서드를 이용하고, MySQL의 update 쿼리문을 이용하여 수정할 수 있습니다.

router.put('/post/:id',  (req, res) => {
    const id = req.params.id;
    const content = req.body.cont;
    const param = [id, content] 
	connection.query("UPDATE User SET id=?, content =? ;", param, function(err, rows, fields){
		if(err) console.log(err);
		console.log(rows);
	})
});

 

 마지막으로 특정 id 값의 데이터를 삭제하고자 할 경우 delete 메서드를 이용하여 삭제를 진행하며, MySQL의 delete 쿼리문을 이용할 수 있습니다.

router.delete('/post/:id',  (req, res) => {
    const param = req.params.id;
	connection.query("DELETE FROM User WHERE id=?;" param, function(err, rows, fields){
		if(err) console.log(err);
		console.log(rows);
	})
});

 

 

 

댓글