Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inserting Records into Table using Node
In this article, we will see how we can insert data into a table using NodeJS. Read the complete article to understand how we can save data into the database table.
Before proceeding, please check the following steps are already executed −
mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql
The above steps are for installing the Node - mysql dependecy in the project folder.
Insert a Record into the Students Table
For adding the new records into the MySQL table, firstly create an app.js file
Now copy-paste the below snippet in the file
Run the code using the following command
>> node app.js
Example
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("DB Connected!");
var sql = "INSERT INTO students (name, address) VALUES ('John', 'Delhi')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Successfully inserted 1 record.");
});
});
Output
After Inserting the record, we will get the following output −
Successfully inserted 1 record.
Insert Multiple Records into the Students Table
For adding new records into the MySQL table, firstly create an app.js file
Now copy-paste the below snippet in the file
Run the code using the following command
>> node app.js
Example
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("DB Connected!");
var sql = "INSERT INTO students (name, address) VALUES ('Pete', 'Mumbai'), ('Amy', 'Hyderabad'), ('Hannah', 'Mumbai'), ('Mike', 'Delhi')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Successfully inserted multiple records into the table.");
});
});
Output
The above program will give the following output after insertion −
Successfully inserted multiple records into the table.