How to use mysql database with a Node Express application

Node Js

Posted on 20 Jul 17 by Vickey
  389



Now days there are many databases in IT industry. For example NoSQL, Mongo, PostgreSQL, Oracle. But if you are working in open source (PHP) you feel comfortable with MySQL database.So if you have started in Node and Express and you are mysql lover then you can use mysql in your projects by installing MySQL npm package. With Express mostly people use mangodb but by installing NPM package we can use MySQL. So Lets start

First of all we will install npm package for MySQL Database. Open your terminal window and locate to your express project directory and run command.

npm install mysql

When the installation complete, we will create a MySQL database connection.

1. In your project root folder, create a file  name as 'database.js' and paste the below code.

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

// CREATE DATABASE CONECTION 

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

connection.connect(function(err) { 
  if (err) throw err 
  console.log('You are now connected with mysql database...') 
}) 

module.exports = connection;

In this file, change your host, database name and password.

2. Open your-project/routes/index.js file import your database file.

var connection = require('../database');

3. Now go to your terminal and run command.

npm start

mak sure your mysql database is running. If you will connect with your mysql database you will see in terminal.

> node ./bin/www 

You are now connected with mysql database...

4. So lets try a mysql query.

router.get('/', function(req, res, next) {
	connection.query('SELECT * FROM users', function(err, results) {
       		 res.send(results);
    
	})

});

Paste this code in your routes/index.js. your index.js file will look like this

var express = require('express');
var router = express.Router();
var connection = require('../database');
var passwordHash = require('password-hash');

/* GET home page. */
router.get('/', function(req, res, next) {
 	connection.query('SELECT * FROM users', function(err, results) {
        res.send(results);
    })
});
module.exports = router;

Start npm again. To see the result go to yor browser and open url http://localhost:3000/


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com