Skip to content

Instantly share code, notes, and snippets.

@mkhizeryounas
Last active March 7, 2018 19:10
Show Gist options
  • Save mkhizeryounas/647aebf07f37aabd5cddce66c45dcb25 to your computer and use it in GitHub Desktop.
Save mkhizeryounas/647aebf07f37aabd5cddce66c45dcb25 to your computer and use it in GitHub Desktop.
/**
* Auther: mkhizeryounas
* Usage: db.query(queryString, paramArray, (err, res) => { console.log(res) });
*/
var mysql = require("mysql");
var keys = require('./keys');
var pool = mysql.createPool({
host : keys.mysql.host,
port : keys.mysql.port,
user : keys.mysql.user,
password : keys.mysql.password,
database : keys.mysql.database,
});
module.exports = {
getConnection (callback) {
pool.getConnection((err, conn) => {
if(err) {
return callback(err);
}
callback(err, conn);
});
},
query (query, params=[], cb) {
this.getConnection((err, conn) => {
conn.release();
if(err) return cb(err, null);
conn.query(query, params, (err, res) => {
if(err) return cb(err, null);
return cb(null, res);
});
});
}
}
@mkhizeryounas
Copy link
Author

mkhizeryounas commented Mar 1, 2018

Express (NodeJS) Mysql connection implementation

Usage

Setup mysql DB connection host, port, username, password & DB name in the dist file.

const db = require('./nodejs-mysql-db-connection'); 

router.get('/method', (request, response) => {
    db.query('SELECT * FROM table WHERE 1', [], (err,res) => {
        response.json(res);
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment