Asked 7 years ago
5 Feb 2017
Views 1551
yogi

yogi posted

how to connect MySQL with express Framework in Node JS

trying to develop website with MySQL at express Framework in Node JS , was using PHP for server side , want to connect MySQL with express Framework in Node JS so i can use to fetch result or insert / update new data.

so how to connect MySQL with express Framework in Node JS ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

first of all download MySQL module for Node JS


npm install mysql 




it install other dependency module like bignumber , readable stream , sql string etc..


Lets connect Node to MySQL
MySQL module provide good set of library to get connection to MySQL


Code
joomla.js

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

connection.connect();

connection.query('SELECT  * from jos_banner', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].url);
});

connection.end();


node joomla
run it and you first connection established with joomla database

Dont forget to setup MySQL and start the MySQL server


Lets integrate it with express framework

i hoping you used express framework before if not please refer : how to use express framework in node JS

const hostname ="127.0.0.1";
const port ="300";
var express=require('express');
var path = require('path');
 
var app=express();

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

connection.connect();

var bannerlist;
//get the banner list
connection.query('SELECT * from jos_banner ', function (error, results, fields) {
    if (error) throw error;
 bannerlist=results;
 
   });
 
//configure app
//setting view engine
app.set('view engine','ejs');
app.set('views',path.join (__dirname , 'view'));

 
//process get request
app.get('/',function(req,res){

res.render('list',{
title : 'My App',
items:bannerlist});
});

// disconnect MySQL
connection.end();

//listen port at express framework
app.listen(port,function(){
   console.log(`ready on port`);
});


view/list.html

<html>
<head>
</head>
<body>
<ul>
 <% for(var i=0;i< items.length;i++) { %>
  <li><%= items[i].bid %> </li>
<% } %>
</ul>
</body>
</html>


it will list all banner id of jos_banner table
Post Answer