Javascript is one of the most popular programming languages , as all other languages like PHP , C# , Python they all provides driver to connect with Mysql Server . And unlike the MongoDB database Mysql also provides it’s module for Nodejs to connect with , as Mysql is also a popular relational database so there’s need to be support for Nodejs .
Mysql’s module mysql i.e., driver for Nodejs helps Nodejs developer to connect with Mysql server , it’s a very easy library to use and implement .
In this article you will learn to connect with Mysql database using Javascript Nodejs in 3 simple steps .
Requirements
We need the below two requirements in order to make connection with Mysql database using Javascript Nodejs .
1 . Mysql Server (we are using XAMPP )
2 . Nodejs installed
Step 1 : Install Mysql Nodejs library
To install the mysql library you need to have Nodejs installed in your system . Run the following command to install mysql library .
npm install mysql
After installation you need to require this module in your main file before making connection to database .
Note : Don’t forgot to start Mysql server before making a connection unless you will face an error.
Step 2 : Make connection to database and execute queries
After successful installation of library you can make connection to database . You can make connection to database in 2 ways
1 . Simple connection
2 . Pooled connection
Simple connection
In simple connection you will use the basic components to make a connection to Mysql database . First of all you need to require the mysql library in file and then with createConnection() pass all the required parameters i.e., host , user , password , database as shown in below example .
var mysql = require('mysql'); // requiring nodejs mysql library
var connection = mysql.createConnection({ // creating database connection
host : 'localhost',
user : 'root',
password : '',
database : 'users_db'
})
// You can refer to this article originally published at
// https://bepractical.tech/easiest-way-to-connect-database-in-javascript-3-simple-steps/
Article link : https://bepractical.tech/easiest-way-to-connect-database-in-javascript-3-simple-steps/
Top comments (0)