Last active
June 27, 2017 10:57
-
-
Save saiumesh535/f595a9840eb5ac480acfa7a7779ffce3 to your computer and use it in GitHub Desktop.
MySQL connector or singleton for express node app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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