Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

사고쳤어요

[Node.js] MySQL 연결하여 사용하기 본문

웹 풀스택

[Node.js] MySQL 연결하여 사용하기

kevinmj12 2025. 2. 26. 16:56

https://www.npmjs.com/package/mysql2

 

mysql2

fast mysql driver. Implements core protocol, prepared statements, ssl and compression in native JS. Latest version: 3.12.0, last published: 2 months ago. Start using mysql2 in your project by running `npm i mysql2`. There are 5217 other projects in the npm

www.npmjs.com

npm을 통해 mysql2 모듈을 설치하여 디비 환경을 연동하여 보자.

먼저 위의 페이지에 나와있는대로 npm install --save mysql2 명령어를 통해 설치를 진행한다.

 

설치가 완료되었으면, 문서에서 소개하는 방법을 참고하여 SQL 쿼리문을 작성해보자.

const mysql = require("mysql2");

const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  database: "youtube",
  password: "", // 비밀번호 입력
});

const sql = "SELECT * FROM `users`";

connection.query(sql, (err, rows, fields) => {
  if (err instanceof Error) {
    console.log(err);
    return;
  }
  console.log(rows);
  console.log(fields);
});

디비에 저장했던 내용들이 성공적으로 불러와졌다!

이제 불러온 데이터들을 사용할 수 있도록 가공하여 보자.

 

rows를 살펴보면 [ ] (array) 안에 { } (json) 형태로 row가 하나씩 들어있는 것을 확인할 수 있다.

console.log(rows[0]); console.log(rows[0].name); 을 실행하면?

다음과 같이 첫 번째 값과 그 이름만이 나오는 것을 볼 수 있다.