Correct way to connect to mySQL from Node.js (at least for me)

April 3rd, 2015 by admin Leave a reply »

Here is the code I used to connect to mySQL from node.js using this library: https://github.com/felixge/node-mysql/

I know he constantly refers to

connection.connect();
and
connection.end();

But I just simply didn’t need those, I do use RedHat openshift for my project so your mileage may vary.

var express = require('express');
var mysql   = require('mysql');

var connection = mysql.createConnection({
  host     : 'MYSQL_DB_HOST',
  user     : 'MYSQL_DB_USERNAME',
  password : 'MYSQL_DB_PASSWORD',
  database : 'dbName'
});

//then down in your app

app = express.createServer();
app.get('/login', function(req, res) {
            connection.query('SELECT * FROM `Users`', function (error, results, fields) {
                  res.send('Results: ' + results.length);
            });
        });

Advertisement

Leave a Reply