3주차 실습 포스팅에서 MySQL과 Express를 연동하는 방법에 대해 잠깐 다루었습니다. 이번 포스팅에서는 MySQL과 Express를 연동하여 실제 Query를 실행할 수 있는 웹 페이지를 만들어보도록 하겠습니다. 참고로 5, 6주차 실습을 한번에 진행하는 이유는, 6주차 실습이 5주차의 내용을 확장하는 실습이었기 때문입니다.
① db 폴더 > Database > week5 폴더를 생성한다.
② cmd 창을 열어 해당경로로 이동한 후, 아래의 명령을 입력한다.
npm init
npm install express mysql2 body-parser nodemon morgan dotenv
npm install @babel/node @babel/core @babel/preset-env
npm link hbs
③ week5를 VSCode에서 열고 구성이 아래와 같게 되도록 파일을 생성한다.
④ sql.js에 아래의 내용을 입력한다.
import mysql from 'mysql2';
require("dotenv").config();
const pool = mysql.createPool({
host: 'localhost',
port: 3306,
user: 'root',
password: '{비밀번호}',
database: 'week4',
});
const promisePool = pool.promise();
// select query
export const selectSql = {
getBuilding: async () => {
const sql = `select * from building`;
const [result] = await promisePool.query(sql);
return result;
},
getDepartment: async () => {
const sql = `select * from department`;
const [result] = await promisePool.query(sql);
return result;
},
getRoom: async () => {
const sql = `select * from room`;
const [result] = await promisePool.query(sql);
return result;
},
getStudent: async () => {
const sql = `select * from student`;
const [result] = await promisePool.query(sql);
return result;
},
getClass: async () => {
const sql = `select * from class`;
const [result] = await promisePool.query(sql);
return result;
},
}
// insert query
export const insertSql = {
setStudent: async (data) => {
const sql = `insert into student values (
"${data.id}", "${data.name}", "${data.email}",
"${data.phone_number}", "${data.department_id}"
)`
console.log(data);
await promisePool.query(sql);
},
};
// update query
export const updateSql = {
updateStudent: async (data) => {
console.log(data);
const sql = `
UPDATE Student
SET id = ${data.id}, name = "${data.name}",
email = "${data.email}", phone_number = "${data.phone_number}",
department_id = "${data.department_id}"
WHERE id = ${data.id}`;
console.log(sql);
await promisePool.query(sql);
},
updateDepartment: async (data) => {
console.log(data);
const sql = `
UPDATE Department
SET id = ${data.id}, name = "${data.name}",
email = "${data.email}", phone_number = "${data.phone_number}"
WHERE id = ${data.id}`;
console.log(sql);
await promisePool.query(sql);
}
};
⑤ home.js에 아래의 내용을 입력한다.
import express from 'express';
import { insertSql } from '../database/sql';
const router = express.Router();
router.get('/', (req, res) => {
res.render('home', { data: " " });
})
router.post('/', (req, res) => {
const vars = req.body;
const data = {
id: vars.id,
name: vars.name,
email: vars.email,
phone_number: vars.phone_number,
department_id: vars.department_id,
};
insertSql.setStudent(data);
})
module.exports = router;
⑥ select.js에 아래의 내용을 입력한다.
import express from 'express';
import { selectSql } from '../database/sql';
const router = express.Router();
router.get('/', async (req, res) => {
const Building = await selectSql.getBuilding();
const Department = await selectSql.getDepartment();
const Room = await selectSql.getRoom();
const Student = await selectSql.getStudent();
const Class = await selectSql.getClass();
res.render('select', {
main_title: "Tables in InhaDB",
title1: "Building",
title2: "Department",
title3: "Room",
title4: "Student",
title5: "Class",
Building,
Department,
Room,
Student,
Class
})
})
module.exports = router;
⑦ update.js에 아래의 내용을 입력한다.
import express from 'express';
import { selectSql, updateSql } from '../database/sql';
const router = express.Router();
router.get('/student', async (_req, res) => {
const student_res = await selectSql.getStudent();
console.log(student_res)
res.render('updateStudent', {
main_title: "UPDATE 'Student' table",
student_res,
});
});
router.post('/student', async (req, res) => {
const vars = req.body;
const data = {
id: vars.id,
name: vars.name,
email: vars.email,
phone_number: vars.phone_number,
department_id: vars.department_id,
}
await updateSql.updateStudent(data);
res.redirect('/update/student');
})
router.get('/department', async (_req, res) => {
const department_res = await selectSql.getDepartment();
console.log(department_res)
res.render('updateDepartment', {
main_title: "UPDATE 'Department' table",
department_res,
});
});
router.post('/department', async (req, res) => {
const vars = req.body;
const data = {
id: vars.id,
name: vars.name,
email: vars.email,
phone_number: vars.phone_number,
}
await updateSql.updateDepartment(data);
res.redirect('/update/department');
})
module.exports = router;
⑧ index.js에 아래의 내용을 입력한다.
import express from 'express';
import logger from 'morgan';
import path from 'path';
import homeRouter from '../routes/home';
import updateRouter from '../routes/update';
import selectRouter from '../routes/select';
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, '/src')));
app.use(express.urlencoded({ extended: false }))
app.use(express.json());
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use('/', homeRouter);
app.use('/update', updateRouter);
app.use('/select', selectRouter);
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`)
});
⑨ home.hbs에 아래의 내용을 입력한다.
<h1>Insert Student</h1>
<form name="student" method="post" action="/">
<div>
<label for="id">Id</label>
<input id="id" name="id" type="text" required placeholder="Id" />
</div>
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" required placeholder="Name" />
</div>
<div>
<label for="email">E-mail</label>
<input id="email" name="email" type="text" placeholder="email" />
</div>
<div>
<label for="phone_number">Phone Number</label>
<input id="phone_number" name="phone_number" type="text"
required placeholder="000-0000-0000" />
</div>
<div>
<label for="department_id">Department Id</label>
<input id="department_id" name="department_id" type="text" required placeholder="department id" />
</div>
<div>
<input type="submit" value="insert" />
</div>
</form>
⑩ layout.hbs에 아래의 내용을 입력한다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inha Database</title>
<style type="text/css">
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
width: 100px;
height: 20px;
}
</style>
</head>
<body>
{{{body}}}
</body>
</html>
⑪ select.hbs에 아래의 내용을 입력한다.
<h1>{{main_title}}</h1>
<!--Building-->
<h2>{{title1}}</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
{{#each Building}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
</tr>
{{/each}}
</table>
<!--Department-->
<h2>{{title2}}</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Phone number</td>
</tr>
{{#each Department}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{phone_number}}</td>
</tr>
{{/each}}
</table>
<!--Room-->
<h2>{{title3}}</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Capacity</td>
<td>Building Id</td>
<td>Department Id</td>
<td>Club Id</td>
</tr>
{{#each Room}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
<td>{{capacity}}</td>
<td>{{Building_id}}</td>
<td>{{department_id}}</td>
<td>{{club_id}}</td>
</tr>
{{/each}}
</table>
<!--Student-->
<h2>{{title4}}</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Phone number</td>
<td>Department Id</td>
</tr>
{{#each Student}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
<td>{{email}}</td>
<td>{{phone_number}}</td>
<td>{{department_id}}</td>
</tr>
{{/each}}
</table>
<!--CLass-->
<h2>{{title5}}</h2>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Professor</td>
<td>Numbers Of Participants</td>
<td>Department Id</td>
<td>Room Id</td>
</tr>
{{#each Class}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
<td>{{Professor}}</td>
<td>{{numbers_of_participants}}</td>
<td>{{department_id}}</td>
<td>{{Room_id}}</td>
</tr>
{{/each}}
</table>
⑫ updateDepartment.hbs에 아래의 내용을 입력한다.
<h1>{{main_title}}</h1>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Phone_number</td>
</tr>
{{#each department_res}}
<form method="post">
<tr>
<td>{{id}}</td>
<td style="display: none"><input type="text" name="id" value="{{id}}"></td>
<td><input type="text" name="name" value={{name}}></td>
<td><input type="text" name="email" value={{email}}></td>
<td><input type="text" name="phonenumber" value={{phone_number}}></td>
<td><input type="submit" value="Modify" formaction="/update/department"></td>
</tr>
</form>
{{/each}}
</table>
⑬ updateStudent.hbs에 아래의 내용을 입력한다.
<h1>{{main_title}}</h1>
<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Phone_number</td>
<td>Department_Id</td>
</tr>
{{#each student_res}}
<form method="post">
<tr>
<td>{{id}}</td>
<td style="display: none"><input type="text" name="id" value="{{id}}"></td>
<td><input type="text" name="name" value={{name}}></td>
<td><input type="text" name="email" value={{email}}></td>
<td><input type="text" name="phone_number" value={{phone_number}}></td>
<td><input type="text" name="department_id" value={{department_id}}></td>
<td><input type="submit" value="Modify" formaction="/update/student"></td>
</tr>
</form>
{{/each}}
</table>
⑭ Babel.confing.json에 아래의 내용을 입력한다.
{
"presets" : ["@babel/preset-env"]
}
⑮ package.json의 scripts 부분을 아래와 같이 수정한다.
"scripts": {
"test" : "echo \"Error: no test specified\" && exit 1",
"start" : "nodemon --exec babel-node ./src/index.js"
},
① localhost:3000으로 접속하면, 아래와 같은 화면이 로드될 것이다.
② 아래와 같이 입력하고 insert 버튼을 클릭해보면, cmd에서 새롭게 insert된 아이템을 확인할 수 있다.
localhost:3000/select로 접속하면, 아래와 같은 화면이 로드될 것이다.
① localhost:3000/update/student로 접속하면, 아래와 같은 화면이 로드될 것이다.
② hyunseop987@naver.com을 hyunseop123@naver.com으로 수정해보자.
③ cmd에서 update된 결과를 확인할 수 있다.
① localhost:3000/update/department로 접속하면, 아래와 같은 화면이 로드될 것이다.
② incom123@inha.ac.kr을 infocom123@inha.ac.kr로 변경해보자.
③ cmd에서 update된 결과를 확인할 수 있다.