Example connect mysql with nodejs

Node.js can be used in database applications.

One of the most popular databases is MySQL.

MySQL Database

To be able experiment with the code examples, you should have MySQL installed on your computer.

You can download a free MySQL database at  https://www.mysql.com/downloads/.

Install MySQL Driver

Once you have MySQL up and running on your computer, you can access it by using Node.js.

To access a MySQL database with Node.js, you need a MySQL driver. This tutorial will use the "mysql" module, downloaded from NPM.

To download and install the "mysql" module, open the Command Terminal and execute the following:

 

C:\Nodejs>npm install mysql

 

Now you have downloaded and installed a mysql database driver.

Node.js can use this module to manipulate the MySQL database:

 

var mysql = require('mysql');

 

Create Connection

Start by creating a connection to the database.

Use the username and password from your MySQL database.

Example: connect mysql

 

var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "11"

});

con.connect(function(err) {

  if (err) throw err;

  console.log("Connected!");

});

 

Run and result:

 

C:\Nodejs>node mysqlConnect.js

Connected!