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.

01var express = require('express');
02var mysql   = require('mysql');
03 
04var connection = mysql.createConnection({
05  host     : 'MYSQL_DB_HOST',
06  user     : 'MYSQL_DB_USERNAME',
07  password : 'MYSQL_DB_PASSWORD',
08  database : 'dbName'
09});
10 
11//then down in your app
12 
13app = express.createServer();
14app.get('/login', function(req, res) {
15            connection.query('SELECT * FROM `Users`', function (error, results, fields) {
16                  res.send('Results: ' + results.length);
17            });
18        });

Advertisement

Leave a Reply