Home » How to use MySQL Database with Node.js?
use mysql database with nodejs

How to use MySQL Database with Node.js?

How to use MySQL Database with Node.js?

In today’s interconnected world, creating dynamic and data-driven web applications is a common requirement. To achieve this, developers often use databases to store, manage, and retrieve information efficiently. MySQL, a popular open-source relational database management system, is a prime choice for many projects. When combined with Node.js, a powerful JavaScript runtime, you can create robust and scalable applications with ease. In this guide, we’ll walk you through the process of integrating MySQL with Node.js to build data-driven applications.

Prerequisites

Before we dive into the details, make sure you have the following prerequisites in place:

  1. Node.js: Install Node.js on your system. You can download it from the official Node.js website.
  2. MySQL Server: Have a MySQL server instance up and running. You can install MySQL locally or use a remote server.
  3. npm: npm is the Node.js package manager. It comes bundled with Node.js.

Step 1: Installing Dependencies

Open your terminal and navigate to your project’s directory. To interact with the MySQL database from Node.js, you’ll need the mysql2 package. Install it using the following command:

npm install mysql2

Step 2: Setting Up Database Connection

Create a new JavaScript file (e.g., db.js) to handle the database connection. Inside this file, require the mysql2 package and establish a connection to your MySQL server:

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'your_host',
  user: 'your_user',
  password: 'your_password',
  database: 'your_database'
});

module.exports = connection;

Replace 'your_host', 'your_user', 'your_password', and 'your_database' with your MySQL server’s details.

Step 3: Performing Database Operations

Now that you have a connection to the database, you can perform various operations like inserting, updating, and querying data.

Inserting Data

const db = require('./db');

const newRecord = {
  name: 'John Doe',
  email: 'john@example.com'
};

db.query('INSERT INTO users SET ?', newRecord, (error, results) => {
  if (error) throw error;
  console.log('New record inserted:', results);
});

Querying Data

db.query('SELECT * FROM users', (error, results) => {
  if (error) throw error;
  console.log('Fetched records:', results);
});

Step 4: Handling Asynchronous Operations

Node.js is designed to work asynchronously. Therefore, it’s crucial to handle asynchronous database operations properly. Promises or async/await can be used for this purpose.

Using Promises

db.promise().query('SELECT * FROM users')
  .then(([rows, fields]) => {
    console.log('Fetched records:', rows);
  })
  .catch(error => {
    throw error;
  });

Using async/await

async function fetchUsers() {
  try {
    const [rows, fields] = await db.promise().query('SELECT * FROM users');
    console.log('Fetched records:', rows);
  } catch (error) {
    throw error;
  }
}

fetchUsers();

Conclusion

Integrating MySQL with Node.js opens up a world of possibilities for creating dynamic and data-driven applications. By following the steps outlined in this guide, you’ve learned how to establish a connection to a MySQL database, perform various database operations, and handle asynchronous operations effectively. With this foundation, you can confidently start building robust, scalable, and efficient applications that leverage the power of MySQL and Node.js.

Resources

MySQL:

  1. Official MySQL Documentation: The official documentation is always a great place to start. It provides comprehensive information and examples.
  2. W3Schools MySQL Tutorial: W3Schools offers interactive tutorials with examples for MySQL.
  3. MySQL Tutorial by TutorialsPoint: Another well-structured tutorial with practical examples.

Node.js and MySQL:

  1. Node.js Official Website: Learn the basics of Node.js, which is a JavaScript runtime used for server-side development.
  2. Node.js MySQL Driver Documentation (mysql2): This is the official MySQL driver for Node.js. The documentation provides examples and usage guides.
  3. Node.js and MySQL Tutorial by W3Schools: W3Schools also has a tutorial on using Node.js with MySQL.
  4. Node.js and MySQL Tutorial by The Net Ninja (YouTube): Video tutorials can be very helpful. The Net Ninja has a series on using Node.js and MySQL.

More Reading

Post navigation

Leave a Comment

Leave a Reply

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

Best Coding Ideas in JavaScript

How to authenticate pages in Vuejs (OIDC)

How to create Full Stack Application with Node.js and React ?

Creating a Simple Express.js Server on Node.js

How to use Authentication in Node.js & React?

Chat Icon