Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active June 27, 2017 10:57
Show Gist options
  • Save saiumesh535/f595a9840eb5ac480acfa7a7779ffce3 to your computer and use it in GitHub Desktop.
Save saiumesh535/f595a9840eb5ac480acfa7a7779ffce3 to your computer and use it in GitHub Desktop.
MySQL connector or singleton for express node app
// getting connection from mysql.js file
// creating new mysql connection and checking it
const mysqlConnection = require('./model/mysql');
const mysql = require('mysql');
app.get('/testmysql', function(req, res) {
console.log(mysqlConnection.name);
mysqlConnection.createConnection().then((connection) => {
let query = "select * from zeus_user";
let table = [];
query = mysql.format(query, table);
connection.query(query, (err, result) => {
if (err) {
res.send("error");
console.log(err.stack);
} else {
// release the connection after its use.
connection.release();
res.json({ "STATUS": true, "RESULT": result });
}
})
}).catch((error) => {
res.send("error");
console.log(error.stack);
});
})
// this is for creating mysql connection
// this will act as your singleton class if your coming from java
// for more information please visit https://www.npmjs.com/package/mysql
var mysql = require('mysql');
const Q = require('q');
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: '',
database: 'database_name'
});
var mysqlConnection = {};
mysqlConnection.createConnection = createConnection;
mysqlConnection.name = "saiumesh";
module.exports = mysqlConnection;
function createConnection() {
let deferred = Q.defer();
pool.getConnection((err, connection) => {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(connection);
}
})
return deferred.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment