2017-12-16 1 views
0

Node.js에 mysql 모듈을 사용하고 있습니다. 내 모델 파일에서 현재 각 메서드에서 연결 상수를 지정하고 있습니다. 그러나 이것은 많은 공간을 차지하고 있으며 이상적이지 않다는 것을 알고 있습니다.Node.js에서 코드 반복을 피하기 위해 MySQL 연결을 넣을 곳

다음은 그 모습입니다.

doSomething:() => { 

    var connection = mysql.createConnection({ 
     host  : config.database.host, 
     database : config.database.database, 
     user  : config.database.user, 
     password : config.database.password 
    }); 

    connection.query(...); 
    connection.destroy(); 

}, 



doSomethingElse:() => { 

    var connection = mysql.createConnection({ 
     host  : config.database.host, 
     database : config.database.database, 
     user  : config.database.user, 
     password : config.database.password 
    }); 

    connection.query(...); 
    connection.destroy(); 


}, 

누구나 정리할 수있는 방법을 권장하고 중복 코드를 줄일 수 있습니까?

답변

0

연결을 한 번 만들고 모듈 내보내기로 전달하십시오.

const mysql = require("mysql"); 

const conn = mysql.createConnection({ 
    host: "localhost", 
    user: "root", 
    password: "", 
    database: "db" 
}); 

module.exports = conn; 

그런 다음 다른 파일로 가져 와서 사용할 수 있습니다.

var dbConnection = require('./dbConnection'); 

dbConnection.query(); 

그러나, 대신 createConnection를 사용하는, 내가 대신 createPool를 사용하는 것이 좋습니다.

단일 연결 공유를 용이하게하기 위해 연결을 풀링하거나 여러 연결을 관리 할 수 ​​있습니다.

const mysql = require("mysql"); 

const conn = mysql.createPool({ 
    host: "localhost", 
    user: "root", 
    password: "", 
    database: "db" 
}); 

module.exports = conn; 

당신은이처럼 사용할 수 있습니다. 테이블에서 데이터를 가져 오는 한 후 연결을 release해야합니다 :

var connectionPool = require('./dbConnection'); 

connectionPool.getConnection((err, connection) => { 
    connection.query('SELECT * FROM table', (error, result) { 
    connection.release(); 
    if(error) throw error; 
    }); 
}); 

는 풀의 모든 연결을 닫으려면 :

connectionPool.end(function (err) { 
    // all connections in the pool have ended 
}); 
+0

당신을 감사합니다! 그리고 연결을 어디에서 끝내겠습니까? – Joel

+0

@Joel 내 편집보기 –

관련 문제