mysql 연결하기_Express

miin·2022년 4월 4일
0

Express & node.js

목록 보기
6/10
post-thumbnail
//db.js

//mysql 변수에 mysql 모듈을 할당
const mysql = require('mysql');

//connection변수에 mysql변수에 있는 createConnection method 호출(객체를 받음)할당
const db = mysql.createConnection({
    host: 'localhost',//mariadb가 존재하는 서버의 주소
    user:'test2',//mariadb의 계정
    password: 'password123@',//mariadb 계정의 비밀번호
    database: 'testDB'//접속 후 사용할 db명
});

module.exports = db;

//main.js
const db = require('./db.js')//db접속 정보가 있는 모듈 가져오기
const http = require('http');

const app = http.createServer(function(request,response){
  //connection.쿼리 메소드를 호출해서(첫번째인자는 sql문, 두번째 인자로 콜백함수)
//첫번째 인자쿼리가 실행되고나서, 두번째 콜백함수가 실행됨
  db.query(`SELECT * FROM test2`, function(err,result){
     //에러가 발생하면 에러에 할당, 테이블내용은 result에 할당)  
  	if(err) console.log('err:', err)
    else console.log('results:', results)
   const html = 
   response.writeHead(200); //응답상태 성공
    response.end(html);//웹에 띄워줄 내용
  });
})

app.listen(4001)//http.createServer()가 할당된 app을 4001로 오픈

0개의 댓글