• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Connect to MySQL Database and performing CRUD Operations using Node.js

  • July 2, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial :-
  • Prerequisites
  • Install Required Packages
  • Require the ‘mysql’ Module
  • Establish a Connection
  • Connect to the MySQL Database
  • Closing the Database Connection
  • Executing Query in MySQL DB
  • Creating a Database
  • Selecting a Database
  • Creating Table using Node
  • Inserting Data from Employee Table using Node
  • Updating Data from Employee Table using Node
  • Deleting Data from Employee Table using Node
Connect to MySQL Database and performing CRUD Operations using Node.js
Connect to MySQL Database and performing CRUD Operations using Node.js

In this tutorial, we will guide you through the process of connecting to a MySQL database using Node.js. Establishing a connection between your Node.js application and MySQL database allows you to perform essential database operations, such as retrieving data, inserting records, updating information, and more.

By following this step-by-step guide, you will be able to connect to your MySQL database seamlessly. So, let’s dive in and get started!



Prerequisites

To follow along with this tutorial, you should have a basic understanding of Node.js and have it installed on your machine. Additionally, make sure you have MySQL installed and running.

To Install SQL Server and MySQL Workbench visit here

Install Required Packages

Before connecting to a MySQL database, ensure that you have the necessary Node.js packages installed. Open your terminal and navigate to your project directory.

Then, execute the following command to install the mysql package:

npm install mysql

Require the ‘mysql’ Module

const mysql = require('mysql');

Establish a Connection

To establish a connection to your MySQL database, create a connection object by passing the required configuration options. Insert the following code snippet in your file:

const connection = mysql.createConnection({
  host: 'localhost', // Replace with your MySQL host
  user: 'your_user', // Replace with your MySQL username
  password: 'your_password', // Replace with your MySQL password
  database: 'your_database' // Replace with your MySQL database name
});

Make sure to replace the placeholder values with your actual MySQL credentials.



Connect to the MySQL Database

Now, let’s connect to the MySQL database using the connection object. Insert the following code snippet below the connection object creation:

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL database: ', err);
    return;
  }
  console.log('Connected to MySQL database!');
});

This code establishes the connection to your MySQL database and logs a success message if the connection is successful. If an error occurs, it will be displayed in the console.

Here, is the complete code to establish a connection:

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
  });
  return connection;
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful'): console.log('Connection to database not successfull');

Run this code using following command:

node index.js

You would be able to see following message once you establish the connection.

Connection to database successful

Closing the Database Connection

We can close the database connection using connection.end() function.

connection.end((err) => {
  if (err) {
    console.error('Error closing connection:', err);
    return;
   }
  console.log('Connection closed.');
});

Here, is the complete code:

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: ''
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful'): console.log('Connection to database not successfull');
let connection_abort = close_connection(connection_live);

Connection to database successful
Connection closed.

Executing Query in MySQL DB

To execute any query in a database from our node application, we just need to use .query() function.

connection.query(query, callback())

Creating a Database

With the MySQL database connection established, you can now create the database

connection.query(`CREATE DATABASE ${databaseName}`, (err) => {
      if (err) {
        console.error('Error creating database:', err);
        return;
      }
      console.log(`Database '${databaseName}' created.`);
});

Here, is the complete code:

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let create_database = (connection, databaseName) => 
{
  connection.query(`CREATE DATABASE ${databaseName}`, (err) => {
    if (err) {
      console.error('Error creating database:', err);
      return;
    }
    console.log(`Database '${databaseName}' created.`);
});
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: ''
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful') : console.log('Connection to database not successful');
connection_live ? create_database(connection_live, 'EmployeeData') : console.log('Connection to database not successful');
connection_live ? close_connection(connection_live) : console.log('No active Connection !');

Above code will do following tasks:

1. Create a Connection with MySQL.
2. If succeeded, it will invoke the function to create a database called ‘EmployeeData‘.
3. Close the connection.

Following would be printed on the console:

Connection to database successful
Database ‘EmployeeData’ created.
Connection closed.

Let’s verify the change from MySQL workspace

Database employeedata created successfully
Database employeedata created successfully


Selecting a Database

Once we create a database, we are free to create some tables within it. To use a database, follow this code:

// Select the created database
connection.query(`USE ${databaseName}`, (err) => {
 if (err) {
   console.error('Error selecting database:', err);
   return;
 }
  console.log(`Database '${databaseName}' selected.`);
});

Please note that now we are going to create a table within this database employeedata and will perform some basic CRUD operations. Hence, we are going to add this database in our config.

Modify create_connection() function as:

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host,
    user: credentials.user, 
    password: credentials.pass, 
    database: credentials.db,
  });
  return connection;
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: 'employeedata'
};

Creating Table using Node

Table Schema
Table Schema
const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let create_table = (connection) => 
{
  
  const query = `
    CREATE TABLE Employee (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(50),
      email VARCHAR(50),
      salary VARCHAR(50)
    );
  `;

  // Execute the table creation query
  connection.query(query, (err) => {
  if (err) {
    console.error('Error creating table:', err);
    return;
  }
  console.log(`Table Employee created.`);
});
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: 'employeedata'
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful') : console.log('Connection to database not successfull');
connection_live ? create_table(connection_live) : console.log('Connection to database not successful')
connection_live ? close_connection(connection_live) : console.log('No active Connection !');

This code demonstrates the process of creating a connection, creating a table, and closing the connection using the MySQL module in Node.js. It provides a structured way to manage the connection and perform table creation operations in a MySQL database.

Now, run this code using following command:

node index.js

Connection to database successful
Table Employee created.
Connection closed.

Let’s verify the change by check our MySQL workspace,

Table created
Table created


Inserting Data from Employee Table using Node

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let insert_into_table = (connection, data) => 
{
 // SQL query to insert data into the table
 const insertQuery = `INSERT INTO employee SET ?`;

 // Execute the data insertion query
 connection.query(insertQuery, data, (err, results) => {
   if (err) {
     console.error('Error inserting data:', err);
     return;
   } 
   else
   {
    console.log('Data Inserted !');
   }
 });
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: 'employeedata'
};

const data = {
  ID: 3123,
  name: 'Shreyansh',
  email: '[email protected]',
  salary: '30 LPA'
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful') : console.log('Connection to database not successful');
connection_live ? insert_into_table(connection_live, data) : console.log('Connection to database not successful')
connection_live ? close_connection(connection_live) : console.log('No active Connection !');

Here’s the output:

Connection to database successful
Data Inserted !
Connection closed.

Let’s verify the changes in our database.

Data Inserted
Data Inserted


Updating Data from Employee Table using Node

Let’s update the salary of employee from 30 LPA to 40 LPA.

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let update_table_data = (connection, updated_data) => 
{
 // SQL query to update data in the table
 const updateQuery = `UPDATE employee SET ? WHERE id = 3123`;

 // Execute the data update query
 connection.query(updateQuery, updated_data, (err, results) => {
   if (err) {
     console.error('Error updating data:', err);
     return;
   }
   console.log('Data updated successfully!');
   console.log('Affected rows:', results.affectedRows);
  });
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: 'employeedata'
};

const data = {
  salary: '40 LPA'
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful') : console.log('Connection to database not successful');
connection_live ? update_table_data(connection_live, data) : console.log('Connection to database not successful')
connection_live ? close_connection(connection_live) : console.log('No active Connection !');

Now, run this code using following command:

node index.js

Here’s the output:

Connection to database successful
Data updated successfully!
Affected rows: 1
Connection closed.

Let’s verify the changes in our database.

salary updated
salary updated


Deleting Data from Employee Table using Node

Let’s try to delete the only record that exists in the table Employee.

const mysql = require('mysql');

let create_connection = (credentials) => 
{
  const connection = mysql.createConnection({
    host: credentials.host, // Replace with your MySQL host
    user: credentials.user, // Replace with your MySQL username
    password: credentials.pass, // Replace with your MySQL password
    database: credentials.db // Replace with your MySQL database name
  });
  return connection;
}

let delete_data = (connection) => 
{
 // SQL query to update data in the table
 const query = `DELETE from employee WHERE id = 3123`;

 // Execute the data update query
 connection.query(query, (err, results) => {
   if (err) {
     console.error('Error updating data:', err);
     return;
   }
   console.log('Data deleted successfully!');
   console.log('Affected rows:', results.affectedRows);
  });
}

let close_connection = (connection) => 
{
  connection.end((err) => {
    if (err) {
      console.error('Error closing connection:', err);
      return;
     }
    console.log('Connection closed.');
  });
}

let credentials = {
  host: 'localhost',
  user: 'root',
  password: '',
  db: 'employeedata'
};

const data = {
  salary: '40 LPA'
};

let connection_live = create_connection(credentials);
connection_live ? console.log('Connection to database successful') : console.log('Connection to database not successful');
connection_live ? delete_data(connection_live, data) : console.log('Connection to database not successful')
connection_live ? close_connection(connection_live) : console.log('No active Connection !');

Now, run this code using following command:

node index.js

O/P

Connection to database successful
Data deleted successfully!
Affected rows: 1
Connection closed.

Let’s verify this change on our database side

No data left
No data left

Phew !! That’s all for now.

You have successfully connected to a MySQL database using Node.js. By following this tutorial, you now have the foundation to interact with your MySQL database, execute queries, and perform various database operations.





Tags: Best practices for MySQL integration with Node.jsConnect to MySQL database with Node.jsConnecting Node.js and MySQL databasemySQL and Node.js integrationMySQL module for Node.jsNode.js MySQL connection exampleNode.js MySQL connection tutorialNode.js MySQL CRUD operationsStep-by-step guide to connect MySQL and Node.jsUsing Node.js to connect to MySQL
  • Previous Simplifying Asynchronous Programming with async/await in Node.js
  • Next Fetching Data from External APIs with Express and Axios: A Comprehensive Guide

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.