How to Insert a record in database in Node JS
Today I will show you how to insert record in database in node js. Here I will use MySQL database. and I created a database named “node_js”, there has a table named “emp” containing columns are id, name, age, email, created_at. Please follow the following steps –
Step 1 : At first open the “node_modules” directory under the project directory, then change this directory in command prompt and use the command “npm install mysql”
Step 2 : Secondly, Make a js file named “databaseConnection.js” in routes folder in project directory. Paste the following code there.
var express = require('express');
var router = express.Router(); var mysql = require(‘mysql’); var conn = mysql.createConnection({ host:’localhost’, user: ‘root’, password: ‘****’, database: ‘node_js’ }); conn.connect(function(err){ if(err) throw err; console.log(‘database Connected’); }); module.exports = conn;
Step 3 : open the index.ejs file under the view directory and make a form containing name, age, email
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> <style> .form{width: 34%;text-align: center;border: 1px solid #000;margin-left: 31%;padding: 10px;} .form p input{padding: 4%;width: 90%;} </style> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> <div class="form"> <form name="frm" action="/insert" method="post"> <% if(success!='') {%> <h3><%= success %></h3> <% } %> <p><input type="text" name="uname" value="" placeholder="Name" required /> </p> <p><input type="number" name="age" value="" placeholder="Age" required /> </p> <p><input type="email" name="email" value="" placeholder="Email" required /> </p> <p><input type="submit" name="submit" value="Submit" /> </p> </form> </div> </div> </body> </html>
Step 4 : Now open the app.js file and set url here according the form action. Add the following code.
app.post('/insert',index);
Here get, post, delete etc methods are available. I used post method because my form method is post. It takes two parameter, the first parameter is for url and second parameter denotes to index.js file under the routes folder.
Step 5 : index.js file under the routes folder, used the following code –
router.post('/insert', function (req, res, next) { var name = req.body.uname; var age=req.body.age; var email = req.body.email; var submit = req.body.submit; var dt = dateTime.create(); var currentDate = dt.format('Y-m-d H:M:S'); console.log(currentDate); if(submit!='') { var db = require('./databaseConnection'); db.query("insert into emp(name, age, email) values('"+name+"', "+age+", '"+email+"' )", function(err, result){ if(err) throw err; res.render('index',{title: 'Insert', success: 'data inserted'}); }); } else { res.render('index',{title:'Insert', success: '', error: 'Please Insert data correctly !'}); } });
Now you can run the project, the record must be inserted into the database.