Wednesday, May 24, 2017

Connecting mysql with Sequelize and Nodejs

Sequelize.js is an ORM (Object/Relational Mapper) which provides easy access to MySQL, MariaDB, SQLite or PostgreSQL databases by mapping database entries to objects and vice versa, just like how Hibernate. Sequelize is easy to learn and has dozens of cool features like synchronization, association, validation, etc. I assume you have Nodejs and MySQL installed.

Let's install Sequelize first

npm install --save sequelize

Now install the connector for the database MySQL

npm install --save mysql

That's all, now let's database connection with the below code. Save the code as mysqlConnector.js

var Sequelize = require('sequelize');  
 const sequelize = new Sequelize('mysql://root:password@localhost:3306/test');  
  .then(() => {  
   console.log('Connection has been established successfully.');  
  .catch(err => {  
   console.error('Unable to connect to the database:', err);  

Now execute the js, to see whether we can establish the connection with mysql. To execute the js, run the below command.

node mysqlConnector.js If we where able to establish the connection it will print 'Connection has been established successfully.'

That's all Happy Programming...!!!