1. MySQL 설치 : https://dev.mysql.com/downloads/windows/installer/8.0.htmlㅇ
npm install mysql
2. test용 database 생성
CREATE DATABASE HOMPAGE;
CREATE TABLE USER (
ID VARCHAR(45) NOT NULL,
PASSWORD VARCHAR(45) NOT NULL,
PRIMARY KEY(ID)
);
CREATE TABLE POST_LIST(
POST_ID INT NOT NULL AUTO_INCREMENT,
TITLE VARCHAR(50) NOT NULL,
CONTENT VARCHAR(50) NOT NULL
);
3. db.js
const mysql = require('mysql'); // mysql module 불러오기
const port = 3000; // 사용할 port number
// createConnection() : mysql db server와 연결하기위한 Connection 객체 생성, 인자 ( db 관련 info )
const connection = mysql.createConnection({
host : 'localhost',
user :'root',
password : 'your db password',
database : 'homepage'
});
// db 연결하기.
connection.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
// connection.query('query',callback )
// db로 query문 전송하고, callback 함수 실행
// results는 query문에 대한 return값을 받아옴
connection.query('SELECT * FROM post_list WHERE post_id=1;',function(error, results, fields){
if(error) throw error;
const queryResult_id = results[0].post_id;
const queryResult_title = results[0].title;
const queryResult_content = results[0].content;
console.log(`DATABASE :
post_id : ${queryResult_id}
title : ${queryResult_title}
content : ${queryResult_content}
`);
});
4. 결과
참고 : https://www.npmjs.com/package/mysql
728x90