Skip to content

Instantly share code, notes, and snippets.

@yalamber
Created May 30, 2013 07:38
Show Gist options
  • Save yalamber/6bd1df0cc27849eb09b3 to your computer and use it in GitHub Desktop.
Save yalamber/6bd1df0cc27849eb09b3 to your computer and use it in GitHub Desktop.
db mysql pool in nodejs
"use strict";
var mysqlClient = require('mysql')
, dbPool = mysqlClient.createPool(require('../config/database'))
, commonHelper = require('../library/commonHelper');
function MyModel(params) {
this.tbl = params.tbl;
this.primary_key = params.primary_key;
this.primary_name = params.primary_name;
this.dbPool = dbPool;
}
module.exports = MyModel;
//primary key
MyModel.prototype.fromPK = function fromPK(pk, callback) {
//I think i can define var t = this here and access it in below function. but will i need to do this for every other functions i define?
this.dbPool.getConnection(function (err, connection) {
//I cannot access this here from main class.
var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_key + " = " + connection.escape(pk);
connection.query(query, callback);
});
};
//primary name
MyModel.prototype.fromPN = function fromPN(pn, callback) {
this.dbPool.getConnection(function (err, connection) {
var query = "SELECT * FROM " + this.tbl + " WHERE " + this.primary_name + " = " + connection.escape(pn);
connection.query(query, callback);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment