node js -mysql INSERT (2)

김준영·2024년 3월 22일

SQL문으로 INSERT 하는 방법

var SQL = 'INSERT INTO topic (title, description, author) VALUES ("Nodejs","Server side Javascript", "Son")';
conn.query(SQL, function(err, rows, fields){
    if (err){
        console.log(err);
    } else {
        console.log(rows);
    }
});
conn.end();

쿼리로 insert 해주고 SELECT 를 해보면 잘 추가된 것을 확인할 수 있다.

InsertID 만 출력하기

var SQL = 'INSERT INTO topic (title, description, author) VALUES ("Nodejs","Server side Javascript", "Son")';
conn.query(SQL, function(err, rows, fields){
    if (err){
        console.log(err);
    } else {
        console.log(rows.insertId); # 변경
    }
});
conn.end();

row.insertId 로 출력해주면, 몇번째 id 가 추가된 것인지 확인가능


Param 로 넘겨줘서 INSERT 하는 방법

var SQL = 'INSERT INTO topic (title, description, author) VALUES (?, ?, ?)';
var params = ['Supervisor','Watcher','Haaland'];
conn.query(SQL, params, function(err, rows, fields){
    if (err){
        console.log(err);
    } else {
        console.log(rows);
    }
});
conn.end();

params 에 배열 형태로 넘겨줘서 insert 해주고 SELECT 해보면 추가된 것을 확인 가능하다. ( 보안과도 굉장히 밀접한 관계 )

.
.
.

참조 링크 ▶︎ 생활코딩

profile
junyoun9dev@gmail.com

0개의 댓글