Node.js MySQL Insert into Table - GeeksforGeeks

07 Oct, 2021
NodeJs: An open-source platform for executing javascript code on the server side. Also, a javascript runtime built on Chrome’s V8 JavaScript engine. It can be downloaded from here. Mysql  An open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is the most popular language for adding, accessing, and managing content in a database. Here we will use the Mysql as a database for our node application. It can be downloaded from here.
In this article, we are going to learn how to insert rows into an SQL table using Node.js.With the help of SQL INSERT Query.
Initialize Node.js project:
npm init
Installing Modules: 
npm install express
npm install mysql
File Structure:
MySQL Database Structure:
gfg_db DATABASE.
gfg_table (id INT AUTO_INCREMENT PRIMARY KEY, 
  name VARCHAR(255), address VARCHAR(255)).
sqlConnection.js
// Importing MySQL moduleconst mysql = require("mysql");  // Creating connectionlet db_con = mysql.createConnection({  host: "localhost",  user: "root",  password: "",  database: "gfg_db"});  // Connect to MySQL serverdb_con.connect((err) => {  if (err) {    console.log("Database Connection Failed !!!", err);  } else {    console.log("connected to Database");  }});  module.exports = db_con;
Anytime we want to make a query we will import the db_con module in that file. This will increase the modularity of our code.
index.js
const express = require("express");const database = require('./sqlConnection');  const app = express();  app.listen(5000, () => {  console.log(`Server is up and running on 5000 ...`);});  // Use Route Function from below Examples Here...  app.get("/", (req, res) => {      // Call Route Function Here...});
Example:
Inserting Single Row: Below is a Route function to insert single row.
Javascript
// Function to insert single row values in// the databaselet singleRowInsert = () => {      let query = `INSERT INTO gfg_table         (name, address) VALUES (?, ?);`;      // Value to be inserted    let userName = "Pratik";    let userAddress = "My Address";      // Creating queries    db_con.query(query, [userName,     userAddress], (err, rows) => {        if (err) throw err;        console.log("Row inserted with id = "            + rows.insertId);    });};
Output:
Console output:
Row inserted with id = 1
Inserting Multiple Rows: Below is a Route function to insert multiple rows.
Javascript
// Function to insert multiple Row in databaselet multipleRowInsert = () => {      // Query to insert multiple rows    let query = `INSERT INTO gfg_table         (name, address) VALUES ?;`;      // Values to be inserted    let values = [        ['Amit', 'Yellow Park'],        ['Rishi', 'Park 38'],        ['Akash', 'Central st 954'],        ['Pratik', 'Road 989'],        ['Mangesh', 'Sideway']    ];      // Executing the query    db_con.query(query, [values], (err, rows) => {        if (err) throw err;        console.log("All Rows Inserted");    });};
Database Output:
Console output:
All Rows Inserted
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript