[NodeJs] MySQL 연동하기 (SELECT/INSERT/UPDATE/DELETE)

2021. 4. 30. 01:55 JavaScript BackEnd/Node.js, Express

 

  • MySQL 모듈
    • npm install mysql
    • require('mysql')

  • MySQL Connection 
var mysql = require('mysql');

var conn = mysql.createConnection({
	host: 'localhost',
	user : 'root',
	password : 'admin',
	database : 'test'
});

conn.connect(function(err){
	if(err){
		console.log(err);
	}else{
		console.log('mysql connected.');
	}
});
  • SELECT
conn.query('SELECT * FROM BOARD', function(err, results, fields){
	//console.log(arguments);
	for(var i=0; i<results.length; i++){
		console.log( results[i]._id);
		console.log(results[i][fields[1].name]);
		console.log(results[i][fields[2].name]);
		console.log(results[i].writer);
	}
});
  • INSERT
conn.query('INSERT INTO BOARD(title, content, writer) '+
			' values( "title-new", "conetn-new", "zzz") ',
			function(err, results, fiels){
	console.log(arguments);
});
  • UPDATE
conn.query('UPDATE BOARD SET writer =? WHERE writer=?',
		['abc', 'aaa'],
		function(err, results, fields){
	console.log(arguments);
});
  • DELETE
var sql = 'DELETE FROM BOARD WHERE writer=?';
conn.query(sql, ['bbb'], function(err, results){
	console.log(arguments);
});

 

출처 : ourcstory.tistory.com/27?category=664896