Programming/웹프로그래밍

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

쌍쌍바나나 2016. 3. 18. 15:02
반응형
  • 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);

    });



    반응형