융융이'Blog

## node.js 와 mySQL 연동 본문

2022이전/node.js

## node.js 와 mySQL 연동

바로퇴장 2020. 1. 6. 17:40

Node.js로 기본적인 데이터베이스를 연동하기 위해서는 express 를 통하여 node.js 기반 웹 모듈을 설치해준다.

npm install express express-generator
express PROJECT_NAME
npm install

다음으로 데이터베이스(mySQL)를 이용하기 위해서 mySQLWorkbench를 설치해준 뒤

database를 만들어주고 사용하고자 하는 table을 만들어준다. 자세한 내용은 mySQL 자료를 확인해 보자.

Localhost, Host, port, password 값을 확인해준뒤 이제 node.js에 적용을 시켜보자

config라는 폴더를 만들어주고 그안에 dbconfig.js 파일을 만들어준다.

const mysql = require('promise-mysql')

const dbConfig = {
    host: "localhost"
    port: 3306,
    user: 'admin',
    password: '*******',
    database: 'testDB',
    dateStrings: 'date',
}

module.exports = mysql.createPool(dbConfig)

Module/pool.js

const poolPromise = require('../config/dbConfig')

module.exports = {
    queryParam_None: async (...args) => {
        const query = args[0]
        let result;
        const pool = await poolPromise;
        try {
            var connection = await pool.getConnection() // connection을 pool에서 하나 가져온다.
            result = await connection.query(query) || null // query문의 결과 || null 값이 result에 들어간다.
        } catch (err) {
            console.log(err)
            connection.rollback(() => {})
        } finally {
            pool.releaseConnection(connection) // waterfall 에서는 connection.release()를 사용했지만, 이 경우 pool.releaseConnection(connection) 을 해준다.
            return result
        }
    },
    queryParam_Arr: async (...args) => {
        const query = args[0]
        const value = args[1] // array
        let result
        try {
            var connection = await pool.getConnection() // connection을 pool에서 하나 가져온다.
            result = await connection.query(query, value) || null // 두 번째 parameter에 배열 => query문에 들어갈 runtime 시 결정될 value
        } catch (err) {
            connection.rollback(() => {})
            next(err)
        } finally {
            pool.releaseConnection(connection) // waterfall 에서는 connection.release()를 사용했지만, 이 경우 pool.releaseConnection(connection) 을 해준다.
            return result
        }
    },
    queryParam_Parse: async (inputquery, inputvalue) => {
        const query = inputquery
        const value = inputvalue
        let result
        try {
            var connection = await pool.getConnection()
            result = await connection.query(query, value) || null
            console.log(result)
        } catch (err) {
            console.log(err)
            connection.rollback(() => {})
            next(err)
        } finally {
            pool.releaseConnection(connection)
            return result
        }
    },
    Transaction: async (...args) => {
        let result = "Success"

        try {
            var connection = await pool.getConnection()
            await connection.beginTransaction()
            await args[0](connection, ...args)
            await connection.commit()
        } catch (err) {
            await connection.rollback()
            console.log("mysql error! err log =>" + err)
            result = undefined
        } finally {
            pool.releaseConnection(connection)
            return result
        }
    }
}

dbtest.js

const express = require('express'); const router = express.Router();
const pool = require('../module/pool');

router.get('/insert', async (req, res) => {
    const table = 'user';
    const fields = 'useridx, id, name, password, phone';
    const questions = `2, 'test', 'test', '1234', '010-0000-0000'`;
    const result = await pool.queryParam_None(`INSERT INTO ${table}(${fields}) VALUES(${questions})`);
    if(!result) {
        res.status(500).send('error');
        return;
    }
    console.log(result);
    res.status(200).send(result);
})

router.get('/select', async (req, res) => {
    const table = 'user';
    const result = await pool.queryParam_None(`SELECT * FROM ${table}`);
    if(!result) {
        res.status(500).send('error');
        return;
    }
    res.status(500).send('error');
})

router.get('/update', async (req, res) => {
const table = 'user';
const result = await pool.queryParam_None(`UPDATE ${table} SET name = 'so
ptTest' where name = 'test'`);
    console.log(result);
    if(!result) {
        res.status(500).send('error');
return; }
    res.status(200).send(result);
})
router.get('/delete', async (req, res) => {
    const table = 'user';
    const result = await pool.queryParam_None(`DELETE FROM ${table} WHERE NAM
E='test'`)
    console.log(result);
    if(!result) {
        res.status(500).send('error');
    return;
    }
    res.status(200).send(result);
})

module.exports = router;

위 와 같이 작성하면 된다. 깔끔하게 이용하고 싶다면 Model이라는 폴더를 만들어 기능별로 구현을 해놓고 불러다 쓰면 좋다.