개발 블로깅/Server&DataBase 개념

[2019.04.29] Mysql 설치방법(맥북 환경) 및 node.js 연동

Hello이뇽 2019. 4. 29. 22:30

 

맥북에서는 Mysql을 엄청 쉽게 설치할 수 있다.

 

# mysql 설치법

brew install mysql

설치 끝.. (mysql은 어느 ㅡ로젝트에서 자주 쓰이므로, 왠만하면 전역 설치를 추천!)

# homebrew 설치법

https://brew.sh/index_ko

 

# mysql 서버 실행 방법

mysql.server start // 서버 켜기

mysql.server stop // 서버 끄기

 

# 터미널에서 서버 접속 방법

mysql -u root -p // -u user명 :root, -p : 패스워드를 입력하곘다는 뜻

 

# mysql 접속 화면

 

# node.js 연동 방법

var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  port     : 3306,
  database : 'yourDatabaseName'
});

connection.connect();

/* 쿼리 결과 값이 필요 없는 경우 */
var query = `insert into users(name) values('name')`;
connection.query(query);

/* 쿼리 결과 값을 받아올 경우 */
var query = `select * from users`;
connection.query(query, function(error, rows, fields) {
  if(!error){
    console.log(rows);
    console.log(JSON.parse(JSON.stringify(rows))) // 이렇게 해야 제대로 object 방식으로 사용 가능
  }else{
    console.log('Error while performing Query.', error);
  }
});
      
      
connection.end();

 

윈도우에서 연동하려면 이것저것 설치해야하는 것을, 맥에서는 그냥 이렇게 사용하면 된다!

 

 

# node.js 연동 후 실행 시 password 어쩌고 에러가 나는 경우

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'

이 명령어를 한번 실행시켜 주면 해결된다..

반응형