How To Connect MySQL Database in Node Js App
In this article, we will explain to you how to connect MySQL database in node js application. If you want to use MySQL server with your node.js application, you need to learn MySQL node.js connection.
We can easily connect MySQL database using MySQL NPM package in node js application. MySQL is a nodejs npm package and it is written in JavaScript so that we can easily connect MySQL with node js.
Node Js Application Setup
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
1 2 3 | mkdir my_node_app cd my_node_app npm init |
Install NPM Package
After the done setup node js application, we will install the express and MySQL npm package. so you can see the following npm command.
1 | npm install express mysql --save |
Create Database Connection
In this step, We will create a config.js file in the node js application. after that, we will configure the database connection.
1 2 3 4 5 6 7 8 9 10 11 12 | var mysql = require('mysql'); var conn = mysql.createConnection({ host: 'host_name', user: 'database_username', password: 'database_password', database: 'database_name' }); conn.connect(function(err) { if (err) throw err; console.log('Database is connected successfully !'); }); module.exports = conn; |
How to Connect Node.js to MySQL Database
In this step, We will create a server.js file and set up the node js application using express.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var express=require('express'); var app = express(); var dbConn = require('./config'); app.get('/get_data',function(req,res){ dbConn.query('SELECT * FROM students', function (err, results) { if(err) { throw err; } else { return res.send({ status: true, data: results}); } }); }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
1 | node server.js |
Now you can run the example using the below Url in the browser.
1 | http://localhost:3000/get_data |