MySQL

NodeJS can also connect to SQL based Databases like MySQL, MS SQL, postgresql, Oracle SQL and Sqlite. To use SQL Database with Node, install database drivers from npm and configure.

In this article, we will learn how to connect NodeJS with MySQL database.

MySQL is open source RDBMS. Top PHP Web application Stacks like WAMP, LAMP, XAMPP also use MySQL as primary database. ( XAMPPP comes with MariaDB now).

NodeJS 0.6 or higher is required to install MySQL in NodeJS.


Install MySQL

MysQL is available on npm as mysql. Install MySQL and include mysql in main app through module.

npm i mysql

MySQL is installed in NodeJS Application.


Configure

            /*mysql.js*/

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'user',
  password : '123456',
  database : 'sample'
});
 
connection.connect();
 
connection.query('SELECT * from tablename', function (error, results, fields) {
  if (error) {throw error;}
  else{console.log('The output is: ', results[0].colname);}
});
 
connection.end();

Run MySQL

mysql connected

node src/mysql