Programming/Node.js
Node.js : MariaDB 연동
파란크리스마스
2019. 3. 2. 00:39
728x90
출처
- Getting Started With the Node.js Connector - MariaDB Knowledge Base
- GitHub - jareddlc/node-datatables: DataTables server-side script for Node.js
- node.js와 MariaDB 연결하기 (조회 테스트) - 삵 (sarc.io)
- Connector/Node.js Promise API - MariaDB Knowledge Base
- Node.js Mysql(MariaDB) 모듈화하기
/config/db_config.js
module.exports = (function() { return { host: "localhost", port : 10312, user: "root", password: "sqldba", database: "simplesns" } })();
/config/dbHelper.js
const mariadb = require('mariadb'); var config = require('./db_config'); // ./는 현재 디렉토리를 나타냅니다 const pool = mariadb.createPool({ host: config.host, port: config.port, user: config.user, password: config.password, database: config.database, connectionLimit: 5 }); function dbHelper() { // this.getConnection = function(callback) { pool.getConnection() .then(conn => { callback(conn); }).catch(err => { //not connected }); }; // this.getConnectionAsync = async function() { try { let conn = await pool.getConnection(); // console.log("conn = " + conn); // { affectedRows: 1, insertId: 1, warningStatus: 0 } return conn; } catch (err) { throw err; } return null; }; // this.sendJSON = function(response, httpCode, body) { var result = JSON.stringify(body); response.send(httpCode, result); }; } module.exports = new dbHelper();
/api/user/UserService.js
var dbHelper = require('../../config/dbHelper'); // https://github.com/jareddlc/node-datatables/blob/master/server.js function UserService() { this.getUserList = function(request, response) { dbHelper.getConnection(function(conn) { conn.query('SELECT * FROM member') .then((results) => { // console.log(results); //[ {val: 1}, meta: ... ] //Output var output = {}; var temp = []; output.datas = results; dbHelper.sendJSON(response, 200, output); }) .then((res) => { console.log('res = '+res); // { affectedRows: 1, insertId: 1, warningStatus: 0 } conn.end(); }) .catch(err => { //handle error console.log(err); conn.end(); }) }); } } module.exports = new UserService();