본문으로 바로가기

Node.js(MySQL) - Chapter 01. 시작하기

category Front-End/- Node.js 2019. 10. 8. 10:24

1. MySQL Database

Node.js 에서 데이터베이스 어플리케이션을 사용할 수 있고, 그 중에서 MySQL이 가장 인기가 많다.

https://www.mysql.com/downloads/ 에서 MySQL을 다운로드 받아서 설치하고, npm 명령어를 이용하여 Node.js 에서 

MySQL 접근을 위한 MySQL 드라이버 모듈을 설치해본다.

npm install mysql

설치가 완료된 모듈은 불러와서 사용한다.

var mysql = require('mysql');

 

2. Create Connection

데이터베이스에 접속 생성을 위해서 사용자와 패스워드를 사용한다.

var mysql = require('mysql');

var con = mysql.createConnection({
	host : "localhost",
	user : "yourname",
	password : "yourpassword"
});

con.connect(function(err) {
	if(err) throw err;
	console.log("Connected!");
});

저장을 하고 실행하면 "Connected" 가 출력되는 것을 확인한다.

 

3. Query a Database

MySQL 데이터베이스로부터 읽고 쓰기위해 "Query"라고 불리는 SQL 문법을 사용한다.

커넥션 객체는 query를 위한 메소드도 가지고 있다.

con.connect(function(err) {
	if(err) throw err;
	console.log("Connected!");
	con.query(sql, function (err, result) {
		if(err) throw err;
		console.log("Result: " + result);
	});
});