이 글에서는 Node.js를 사용하여 MySQL 데이터베이스의 레코드를 업데이트하는 방법을 알아봅니다. Node.js 서버에서 MySQL 테이블의 값을 동적으로 변경할 수 있으며, 업데이트 후 SELECT 문을 실행하면 레코드가 정상적으로 수정되었는지 확인할 수 있습니다.
사전 준비 사항
본격적인 예제에 앞서 아래 명령어가 이미 실행되어 있는지 확인하세요.
mkdir mysql-test– 프로젝트 폴더 생성cd mysql-test– 폴더 이동npm init -y– package.json 초기화npm install mysql– Node.js용 MySQL 드라이버 설치
위 과정은 프로젝트 폴더에 node-mysql 의존성을 설치하는 단계입니다.
Students 테이블의 레코드 업데이트하기
- 기존 레코드를 수정하려면 먼저
app.js파일을 생성합니다. - 아래 코드 스니펫을 파일에 복사해서 붙여넣습니다.
- 다음 명령어로 코드를 실행합니다.
>> node app.js
예제 1: 이름으로 조건을 걸어 업데이트
// NPM에서 MySQL 의존성 불러오기
var mysql = require('mysql');
// MySQL 연결 생성
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';"
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
});실행 결과
1 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 1, // 업데이트된 행(row) 수를 반환합니다.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0', // 일치한 행 수를 반환합니다.
protocol41: true,
changedRows: 1 }결과 객체인 OkPacket에서 affectedRows는 실제로 수정된 행의 개수를, message는 조건에 일치한 행의 정보를 담고 있습니다.
예제 2: 기존 값으로 조건을 걸어 여러 레코드 업데이트
WHERE 절의 조건을 바꾸면 한 번의 쿼리로 여러 레코드를 동시에 수정할 수도 있습니다. 아래 예제는 주소가 'Delhi'인 모든 학생의 주소를 'Bangalore'로 변경합니다.
// NPM에서 MySQL 의존성 불러오기
var mysql = require('mysql');
// MySQL 연결 생성
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// address가 'Delhi'인 레코드의 주소를 업데이트
var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';"
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
});실행 결과
3 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 3, // 업데이트된 행(row) 수를 반환합니다.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 3 Changed: 3 Warnings: 0', // 일치한 행 수를 반환합니다.
protocol41: true,
changedRows: 3 }정리
Node.js에서 mysql 모듈을 사용하면 con.query() 메서드 하나로 UPDATE 쿼리를 손쉽게 실행할 수 있습니다. WHERE 절 조건에 따라 단일 레코드만 수정할 수도 있고, 여러 레코드를 한 번에 변경할 수도 있습니다. 실무에서는 SQL 인젝션을 방지하기 위해 문자열을 직접 조합하기보다 플레이스홀더(?)와 파라미터 바인딩 방식을 사용하는 것이 안전하다는 점도 함께 기억해 두세요.