NodeJs - MariaDB 연동하기
NodeJs에서 마리아 DB를 사용해보자.
1. 마리아DB 설치
마리아DB 홈페이지에서 마리아DB를 설치합니다.
2. DB 및 테이블 생성
테스트 DB와 테이블을 생성한 후 샘플데이터를 Insert합니다.
1 2 3 4 5 6 7 8 9 10 11 12 DROP DATABASE IF EXISTS nodejs_test; CREATE DATABASE nodejs_test; DROP USER IF EXISTS nodejs_admin; CREATE USER nodejs_admin@ '%' IDENTIFIED BY 'admin' ; GRANT ALL PRIVILEGES ON nodejs_test. * to nodejs_admin@ '%' ; USE nodejs_test; DROP TABLE IF EXISTS users; CREATE TABLE users ( user_key INT NOT NULL AUTO_INCREMENT PRIMARY KEY , user_id VARCHAR ( 128 ) UNIQUE NOT NULL ); INSERT INTO users(user_id) VALUES ( 'TEST01' ); cs
3. Nodejs 프로젝트 생성
CMD 혹은 powershell을 실행 후 workspace로 이동합니다.
npm init을 실행합니다.
프로젝트 관련 여러 사항을 묻습니다. 적당히 입력하고 넘어갑시다.
해당 작업을 수행하면 package.json 파일이 입력된 값에 의해 자동으로 생성됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 { "name" : "mariadb-test" , "version" : "1.0.0" , "description" : "mariadb connection testing project." , "main" : "index.js" , "scripts" : { "test" : "echo \"Error: no test specified\" && exit 1" } , "author" : "smoh" , "license" : "ISC" } Colored by Color Scripter cs
4. 커넥터 설치하기
npm install --save mariadb 를 수행하여 마리아DB 커넥터를 설치합니다.
--save를 입력하면 설치한 모듈정보가 자동으로 입력됩니다.
5. NodeJs를 통해 MariaDB 사용하는 코드 작성
커넥터를 사용하는 소스를 작성합니다.
mariaDBConn.js
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 const mariadb = require( 'mariadb' ); const vals = require( './consts.js' ); const pool = mariadb.createPool({ host: vals.DBHost, port:vals.DBPort, user: vals.DBUser, password: vals.DBPass, connectionLimit: 5 }); async function GetUserList(){ let conn, rows; try { conn = await pool.getConnection(); conn.query( 'USE nodejs_test' ); rows = await conn.query( 'SELECT * FROM users' ); } catch (err){ throw err; } finally{ if (conn) conn.end(); return rows[ 0 ]; } } module.exports = { getUserList: GetUserList } Colored by Color Scripter cs
** 접속정보는 별도 모듈에 저장해뒀습니다. 실제 사용시 pool내의 정보를 변경해 주시기 바랍니다.
6. MariaDB 커넥터 모듈을 사용해 유저 리스트를 가져오는 코드 작성
DB에 있는 정보를 가져와 봅시다.
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const mdbConn = require( './mariaDBConn.js' ) const express = require( 'express' ); const app = express(); mdbConn.getUserList() .then((rows) = > { console .log(rows); }) . catch ((errMsg) = > { console .log(errMsg); }); const port = process.env.PORT | | 3000 ; app.listen(port, () = > { console .log(`listening on ${port}`); }); Colored by Color Scripter cs
** express 프레임워크를 사용했습니다. 실행전에 express 프레임워크를 설치해 주시기 바랍니다.
7. 실행 및 결과 확인.
실행 결과는 다음과 같습니다.
from http://www.smoh.kr/202 by ccl(A)
댓글
댓글 쓰기