Dark Mode
Image

Node.Js Create Connection with MySQL

We can use Node.js in database applications. Here we use MySQL as a database with Node.js.

Install MySQL on your computer.

You can download it from here https://www.mysql.com/downloads/.

Once the MySQL is installed and running, you can access it by using Node.js.

Install MySQL Driver

You have to install MySQL driver to access a MySQL database with Node.js. Download MySQl module from npm.

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

  1. npm install mysql  

Create connection with mysql 1


Create Connection

Create a folder named "DBexample". In that folder create a js file named "connection.js" having the following code:

  1. var mysql = require('mysql');  
  2. var con = mysql.createConnection({  
  3.   host: "localhost",  
  4.   user: "root",  
  5.   password: "12345"  
  6. });  
  7. con.connect(function(err) {  
  8.   if (err) throw err;  
  9.   console.log("Connected!");  
  10. });  

Now open the command terminal and use the following command:

Node connection.js

Create connection with mysql 2

Now Node.js is connected with MySQL.

Comment / Reply From