1. MySQL 설치 : https://dev.mysql.com/downloads/windows/installer/8.0.htmlㅇ
MySQL :: Download MySQL Installer
Select Operating System: Select Operating System… Microsoft Windows Select OS Version: All Windows (x86, 32-bit) Windows (x86, 32-bit), MSI Installer 8.0.26 2.4M (mysql-installer-web-community-8.0.26.0.msi) MD5: eaddc383a742775a5b33a3783a4890fb | Signatu
dev.mysql.com
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
mysql
A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.
www.npmjs.com
728x90