HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
프론트엔드 스쿨 교안(1기)
/
📝
Node
/
📝
1. MySQL 연동 흐름(cloud 사용)
📝

1. MySQL 연동 흐름(cloud 사용)

1. DB 생성하고 데이터 넣기2. 게시판 만들기3. 홈페이지 꾸미기(Bootstrap)4. 메뉴 만들고 id, title, description 출력하기5. 모듈 만들기참고사항
  • 해당 글은 생활코딩 글에 기반하고 있습니다.
  • 연동 흐름을 알려드리기 위해 작성된 글입니다. 실무에서는 express와 시퀄라이즈 ORM을 사용합니다.
  • 복사를 하실 때 mysql> 부분은 빼고 복사를 하셔야 합니다.
  • 최종 동작 확인 21년 12월 29일

1. DB 생성하고 데이터 넣기

npm init --yes npm install --save mysql // 모든 의존성 추가 npm install sanitize-html // 보안(원치 않는 태그 작동 못하도록)
notion image
 
 
아래 입력을 터미털에서 입력해 주세요. 설치하는 중간에 Y를 입력해야 하는 창이 뜨게 됩니다. Y를 입력해 주세요.
sudo apt-get install php7.3-mysql // 이 명령어는 기입 안하셔도 됩니다. service mysql restart mysql -uroot -p 비밀번호 입력 : 123456
 
이제 SQL 구문을 사용할 수 있는 곳으로 들어오게 된 것입니다!
  1. DB를 생성합니다. (CREATE DATABASE testdb;)
  1. 생성된 DB를 확인합니다. (SHOW DATABASES;)
  1. 생성된 DB를 사용합니다. (USE testdb;)
mysql> CREATE DATABASE testdb; mysql> SHOW DATABASES; mysql> USE testdb;
 
이제 생성된 DB 안에 TABLE을 생성하도록 하겠습니다.
mysql> CREATE TABLE testtable ( id int(11) NOT NULL AUTO_INCREMENT, title varchar(30) NOT NULL, description text, created datetime NOT NULL, PRIMARY KEY(id) ) ENGINE=InnoDB;
 
생성된 TABLE에 데이터를 삽입합니다. test로 3개 정도의 데이터를 넣도록 하겠습니다.
INSERT INTO testtable (title, description, created) VALUES ('Python', 'Python is an interpreted, high-level and general-purpose programming language. Python design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale project.', NOW()); INSERT INTO testtable (title, description, created) VALUES ('HTML', 'Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript.', NOW()); INSERT INTO testtable (title, description, created) VALUES ('CSS', 'Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language such as HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.', NOW()); INSERT INTO testtable (title, description, created) VALUES ('JAVA', 'Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere (WORA),[17] meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.', NOW()); INSERT INTO testtable (title, description, created) VALUES ('Javascript', 'JavaScript[6] often abbreviated as JS, is a programming language that conforms to the ECMAScript specification.[7] JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.', NOW());
mysql> SELECT * FROM testtable;
 
mysql> create user 'nodejs'@'%' identified by '123456';
 
mysql> select host, user from mysql.user;
 
mysql> grant all privileges on testdb.* to 'nodejs'@'%';
 
mysql> flush privileges;
 
  • 설정이 끝났으니 나갑니다.
mysql> exit
 
  • nodejs라는 폴더를 만들고 mysql.js파일을 만들어주세요.
// nodejs/mysql.js var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'nodejs', password : '123456', database : 'testdb' }); connection.connect(); connection.query('select * from testtable', function (error, results, fields) { if (error){ console.log(error) }; console.log(results); }); connection.end();
 
notion image
 
lib/template.js
module.exports = { HTML:function(title, list, body, control){ return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} ${control} ${body} </body> </html> `; },list:function(filelist){ var list = '<ul>'; var i = 0; while(i < filelist.length){ list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`; i = i + 1; } list = list+'</ul>'; return list; } }
 
 

2. 게시판 만들기

  • 홈 폴더에 main.js를 만들어줍니다.
var http = require('http'); var fs = require('fs'); var url = require('url'); var qs = require('querystring'); var template = require('./lib/template.js'); var path = require('path'); var mysql = require('mysql'); var db = mysql.createConnection({ host:'localhost', user:'nodejs', password:'123456', database:'testdb' }); db.connect(); var app = http.createServer(function(request,response){ var _url = request.url; var queryData = url.parse(_url, true).query; var pathname = url.parse(_url, true).pathname; if(pathname === '/'){ if(queryData.id === undefined){ db.query(`SELECT * FROM testtable`, function(error,notices){ var title = notices[0].title; var description = notices[0].description; var list = template.list(notices); var html = template.HTML(title, list, `<h2>${title}</h2>${description}`, `<a href="/create">create</a>` ); response.writeHead(200); response.end(html); }); } } else { response.writeHead(404); response.end('Not found'); } }); app.listen(3000);
 

3. 홈페이지 꾸미기(Bootstrap)

lib/template.js
module.exports = { HTML:function(title, list, body, control){ return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} <hr> ${control} <hr> ${body} </body> </html> `; },list:function(filelist){ var list = '<table class="table table-hover"><thead><tr><td>contents</td></tr></thead><tbody>'; var i = 0; while(i < filelist.length){ list = list + `<tr><td><a href="/?id=${filelist[i]}">${filelist[i]}</a></td></tr>`; i = i + 1; } list = list+'</tbody></table>'; return list; } }
 

4. 메뉴 만들고 id, title, description 출력하기

  • 기존에 만들었던 template 파일을 수정하는 것입니다.
module.exports = { HTML:function(title, list, body, control){ return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> </head> <body> <div class="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm"> <h5 class="my-0 mr-md-auto font-weight-normal">Company name</h5> <nav class="my-2 my-md-0 mr-md-3"> <a class="p-2 text-dark" href="#">Features</a> <a class="p-2 text-dark" href="#">Enterprise</a> <a class="p-2 text-dark" href="#">Support</a> <a class="p-2 text-dark" href="#">Pricing</a> </nav> <a class="btn btn-outline-primary" href="#">Sign up</a> </div> <h1><a href="/">Notice</a></h1> ${list} <hr> ${control} <hr> ${body} </body> </html> `; },list:function(filelist){ var list = '<table class="table table-hover"><thead><tr><th>id</td><th>title</th><th>contents</th></tr></thead><tbody>'; var i = 0; while(i < filelist.length){ list = list + `<tr> <td><a href="/?id=${filelist[i].id}">${filelist[i].id}</a></td> <td>${filelist[i].title}</td> <td>${filelist[i].description}</td> </tr>`; i = i + 1; } list = list+'</tbody></table>'; return list; } }
 
여기까지 진행하시고, 실습해보세요. 터미널에서 node main.js로 실행해보세요.
 

 

5. 모듈 만들기

var http = require('http'); var fs = require('fs'); var url = require('url'); var qs = require('querystring'); var template = require('./lib/template.js'); var calculate = require('./lib/calculate.js'); var path = require('path'); var mysql = require('mysql'); var db = mysql.createConnection({ host:'localhost', user:'nodejs', password:'123456', database:'testdb' }); db.connect(); var app = http.createServer(function(request,response){ var _url = request.url; var queryData = url.parse(_url, true).query; var pathname = url.parse(_url, true).pathname; if(pathname === '/'){ if(queryData.id === undefined){ db.query(`SELECT * FROM testtable`, function(error,topics){ var title = topics[0].title; var description = topics[0].description; var list = template.list(topics); var html = template.HTML(title, list, `<h2>${title}</h2>${description}`, `<a href="/create">create</a>` ); var result = calculate.add(100, 10); response.writeHead(200); response.end(`100 + 10 : ${result}`); }); } } else { response.writeHead(404); response.end('Not found'); } }); app.listen(3000);
/lib/calculate.js
module.exports = { add:function(a, b){ return a + b; },mul:function(a, b){ return a * b; } }

 
 
 

참고사항

기존코드
main.js
var http = require('http'); var fs = require('fs'); var url = require('url'); var qs = require('querystring'); function templateHTML(title, list, body, control){ return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} ${control} ${body} </body> </html> `; } function templateList(filelist){ var list = '<ul>'; var i = 0; while(i < filelist.length){ list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`; i = i + 1; } list = list+'</ul>'; return list; } var app = http.createServer(function(request,response){ var _url = request.url; var queryData = url.parse(_url, true).query; var pathname = url.parse(_url, true).pathname; if(pathname === '/'){ if(queryData.id === undefined){ fs.readdir('./data', function(error, filelist){ var title = 'Welcome'; var description = 'Hello, Node.js'; var list = templateList(filelist); var template = templateHTML(title, list, `<h2>${title}</h2>${description}`, `<a href="/create">create</a>` ); response.writeHead(200); response.end(template); }); } else { fs.readdir('./data', function(error, filelist){ fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){ var title = queryData.id; var list = templateList(filelist); var template = templateHTML(title, list, `<h2>${title}</h2>${description}`, ` <a href="/create">create</a> <a href="/update?id=${title}">update</a> <form action="delete_process" method="post"> <input type="hidden" name="id" value="${title}"> <input type="submit" value="delete"> </form>` ); response.writeHead(200); response.end(template); }); }); } } else if(pathname === '/create'){ fs.readdir('./data', function(error, filelist){ var title = 'WEB - create'; var list = templateList(filelist); var template = templateHTML(title, list, ` <form action="/create_process" method="post"> <p><input type="text" name="title" placeholder="title"></p> <p> <textarea name="description" placeholder="description"></textarea> </p> <p> <input type="submit"> </p> </form> `, ''); response.writeHead(200); response.end(template); }); } else if(pathname === '/create_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); var title = post.title; var description = post.description; fs.writeFile(`data/${title}`, description, 'utf8', function(err){ response.writeHead(302, {Location: `/?id=${title}`}); response.end(); }) }); } else if(pathname === '/update'){ fs.readdir('./data', function(error, filelist){ fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){ var title = queryData.id; var list = templateList(filelist); var template = templateHTML(title, list, ` <form action="/update_process" method="post"> <input type="hidden" name="id" value="${title}"> <p><input type="text" name="title" placeholder="title" value="${title}"></p> <p> <textarea name="description" placeholder="description">${description}</textarea> </p> <p> <input type="submit"> </p> </form> `, `<a href="/create">create</a> <a href="/update?id=${title}">update</a>` ); response.writeHead(200); response.end(template); }); }); } else if(pathname === '/update_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); var id = post.id; var title = post.title; var description = post.description; fs.rename(`data/${id}`, `data/${title}`, function(error){ fs.writeFile(`data/${title}`, description, 'utf8', function(err){ response.writeHead(302, {Location: `/?id=${title}`}); response.end(); }) }); }); } else if(pathname === '/delete_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); var id = post.id; fs.unlink(`data/${id}`, function(error){ response.writeHead(302, {Location: `/`}); response.end(); }) }); } else { response.writeHead(404); response.end('Not found'); } }); app.listen(3000);
data/CSS 파일
hello css
data/HTML 파일
hello html
data/javascript 파일
hello js
readdir.js 파일
var testFolder = './data'; var fs = require('fs'); fs.readdir(testFolder, function(error, filelist){ console.log(filelist); })
 

 
생활코딩의 최종코드입니다.
var http = require('http'); var fs = require('fs'); var url = require('url'); var qs = require('querystring'); var template = require('./lib/template.js'); var path = require('path'); var sanitizeHtml = require('sanitize-html'); var mysql = require('mysql'); var db = mysql.createConnection({ host:'localhost', user:'root', password:'111111', database:'opentutorials' }); db.connect(); var app = http.createServer(function(request,response){ var _url = request.url; var queryData = url.parse(_url, true).query; var pathname = url.parse(_url, true).pathname; if(pathname === '/'){ if(queryData.id === undefined){ db.query(`SELECT * FROM topic`, function(error,topics){ var title = 'Welcome'; var description = 'Hello, Node.js'; var list = template.list(topics); var html = template.HTML(title, list, `<h2>${title}</h2>${description}`, `<a href="/create">create</a>` ); response.writeHead(200); response.end(html); }); } else { db.query(`SELECT * FROM topic`, function(error,topics){ if(error){ throw error; } db.query(`SELECT * FROM topic WHERE id=?`,[queryData.id], function(error2, topic){ if(error2){ throw error2; } var title = topic[0].title; var description = topic[0].description; var list = template.list(topics); var html = template.HTML(title, list, `<h2>${title}</h2>${description}`, ` <a href="/create">create</a> <a href="/update?id=${queryData.id}">update</a> <form action="delete_process" method="post"> <input type="hidden" name="id" value="${queryData.id}"> <input type="submit" value="delete"> </form>` ); response.writeHead(200); response.end(html); }) }); } } else if(pathname === '/create'){ db.query(`SELECT * FROM topic`, function(error,topics){ var title = 'Create'; var list = template.list(topics); var html = template.HTML(title, list, ` <form action="/create_process" method="post"> <p><input type="text" name="title" placeholder="title"></p> <p> <textarea name="description" placeholder="description"></textarea> </p> <p> <input type="submit"> </p> </form> `, `<a href="/create">create</a>` ); response.writeHead(200); response.end(html); }); } else if(pathname === '/create_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); db.query(` INSERT INTO topic (title, description, created, author_id) VALUES(?, ?, NOW(), ?)`, [post.title, post.description, 1], function(error, result){ if(error){ throw error; } response.writeHead(302, {Location: `/?id=${result.insertId}`}); response.end(); } ) }); } else if(pathname === '/update'){ db.query('SELECT * FROM topic', function(error, topics){ if(error){ throw error; } db.query(`SELECT * FROM topic WHERE id=?`,[queryData.id], function(error2, topic){ if(error2){ throw error2; } var list = template.list(topics); var html = template.HTML(topic[0].title, list, ` <form action="/update_process" method="post"> <input type="hidden" name="id" value="${topic[0].id}"> <p><input type="text" name="title" placeholder="title" value="${topic[0].title}"></p> <p> <textarea name="description" placeholder="description">${topic[0].description}</textarea> </p> <p> <input type="submit"> </p> </form> `, `<a href="/create">create</a> <a href="/update?id=${topic[0].id}">update</a>` ); response.writeHead(200); response.end(html); }); }); } else if(pathname === '/update_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); db.query('UPDATE topic SET title=?, description=?, author_id=1 WHERE id=?', [post.title, post.description, post.id], function(error, result){ response.writeHead(302, {Location: `/?id=${post.id}`}); response.end(); }) }); } else if(pathname === '/delete_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); db.query('DELETE FROM topic WHERE id = ?', [post.id], function(error, result){ if(error){ throw error; } response.writeHead(302, {Location: `/`}); response.end(); }); }); } else { response.writeHead(404); response.end('Not found'); } }); app.listen(3000);