Search code examples
node.jsexpress

Connecting to database in Express


Trying to connect to database using Express

  • I am new to Express(I have used NODEJS),
  • I am trying to connect to database and display a simple JSON as the resultant output
  • I tried the below code

var express = require('express')
  , http = require('http');

var app = express();

var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: "root",
        database: 'restaurant'
});

// all environments
app.set('port', process.env.PORT || 7002);


app.get('/',function(request,response){
connection.query('SELECT * FROM restaurants', function(err, rows, fields)

        {
                console.log('Connection result error '+err);
                console.log('no of records is '+rows.length);
                        response.writeHead(200, { 'Content-Type': 'application/json'});
                response.end(JSON.stringify(rows));
        });

} );

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Error::

var connection = mysql.createConnection({
                 ^
ReferenceError: mysql is not defined

Error tells mysql module is absent, But i have installed mysql module using::

npm install mysql 

Still no change in error Any ideas


Solution

  • You're missing the mysql module.

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

    But also you need to connect():

    connection.connect();
    

    Before you start querying the database.

    All-together now for laziness:

    var express = require('express')
      , http = require('http')
      , mysql = require('mysql'); // <---- HERE
    
    var app = express();
    
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: "root",
        database: 'restaurant'
    });
    
    connection.connect(); // <---- AND HERE
    
    // all environments
    app.set('port', process.env.PORT || 7002);
    
    
    app.get('/',function(request,response){
    connection.query('SELECT * FROM restaurants', function(err, rows, fields)
    
        {
                console.log('Connection result error '+err);
                console.log('no of records is '+rows.length);
                        response.writeHead(200, { 'Content-Type': 'application/json'});
                response.end(JSON.stringify(rows));
        });
    
    } );
    
    http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port ' + app.get('port'));
    });