Edward Ruchevits
Edward Ruchevits

Reputation: 6696

How to execute MySQL queries in node.js views?

I have imported mysql module in my app.js:

var mysql = require('mysql');

Then I set mysql configuration:

// Database configuration

var HOST            = 'localhost';
var PORT            = 3306;
var MYSQL_USER      = 'root';
var MYSQL_PASS      = 'pass';
var DATABASE        = 'ruchevits_website';

Created mysql client object:

// Create database client

var db = mysql.createClient({
    host:       HOST,
    port:       PORT,
    user:       MYSQL_USER,
    password:   MYSQL_PASS
});

And selected my database:

// Use database

db.query('use ' + DATABASE);

So, now I can execute queries like:

db.query('select id, firstname, lastname from mytable', function(err, result, fields){
    if (err)
    {
        throw err;
    }
    else
    {
        console.log('Selected people:');
        for (var i in result)
        {
            var people = result[i];
            console.log(people.firstname + ' ' + people.lastname);
        }
    }
});

But it is inconvenient to execute all queries in app.js.

I want to execute them in specific routes files in the section:

exports.index = function(req, res)
{
    // MySQL query

    res.render('resume', {
        title: 'Resume'
    });
};

What is the correct way to do that?

I need to use db object not in app.js file. Actually, the question is how to pass it?

Upvotes: 0

Views: 5313

Answers (1)

Chris
Chris

Reputation: 4225

Create a module and export a function that returns the db object.

in dbConnection.js

var mysql = require('mysql');
var db = null;
module.exports = function () {
    if(!db) {
        db = mysql.createClient({
            host:       HOST,
            port:       PORT,
            user:       MYSQL_USER,
            password:   MYSQL_PASS
        });
    };
    return db;
};

use it with var db = require('./dbConnection')(); where ever you need it. Also check out Node.js module caching feature http://nodejs.org/api/modules.html#modules_caching.

Upvotes: 2

Related Questions