프로그래밍/Node.js

Node.js MySQL 연동 - INSERT

채윤아빠 2021. 5. 22. 00:44
728x90
반응형

nodejs에서 MySQL을 연동하는 간략한 방법에 대하여 정리해 둡니다.

데이터 추가 (INSERT)

기본적으로 데이터베이스 서버와 연결을 하고, 간단한 쿼리를 실행하는 예제는 아래와 같습니다.

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    password : 'secret',
    database : 'my_db'
});

connection.connect();

connection.query('INSERT INTO MEMBER VALUES ( ?, ?, ?, ? );'
        , ['login_id', 'password', 'member_name', 'email']
        , function (error, results, fields) {
    if (error)
        throw error;
    let member_no = results.insertId;
    console.log('The new member_no: ', member_no);

    connection.end();
});

데이터베이스 설정에 문제가 없다면, 실행 결과는 다음과 같습니다.

The new member_no: 2

"INSERT"할 정보의 각 속성을 컬럼 인자로 전달하기 위하여 "?" 문자를 이용합니다. "INSERT"할 컬럼 데이터 인자는 쿼리문 다음에 배열로 전달합니다.

 

connection.query() 함수의 실행 결과로 받는 "results"에 "INSERT" 쿼리의 실행 결과 정보를 받게 됩니다.


MariaDB의 "AUTO_INCREMENT"가 지정된 "member_no" 컬럼에 새로 삽입된 번호는 "insertId" 속성을 통하여 얻을 수 있습니다.

 

아래와 같이 MariaDB의 "LAST_INSERT_ID()" 함수를 실행한 결과로도 얻을 수 있습니다.

SELECT LAST_INSERT_ID();

참고 : https://github.com/mysqljs/mysql#multiple-statement-queries