MYSQLNode Js

Creating a connection between Node.js and MySQL

Node.js is a powerful server-side JavaScript runtime that allows developers to build scalable and efficient web applications. When working with databases, one common choice is MySQL, a popular relational database management system. In this guide, we’ll walk through the steps to create a connection between Node.js and MySQL.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  1. Node.js
  2. MySQL

Step 1: Install MySQL Package

To interact with MySQL from Node.js, we need a MySQL package. One of the widely used packages is mysql2. Install it using npm (Node Package Manager) with the following command:

npm install mysql2

Step 2: Set Up MySQL Database

Ensure you have a MySQL database created, and you know the connection details such as host, user, password, and database name.

Step 3: Create a Node.js Script

Now, let’s create a Node.js script to establish a connection with the MySQL database. Create a file, for example, app.js, and add the following code:

// Import the MySQL package
const mysql = require('mysql2');

// Create a connection pool
const pool = mysql.createPool({
  host: 'your-mysql-host',
  user: 'your-mysql-user',
  password: 'your-mysql-password',
  database: 'your-mysql-database',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

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

  // Release the connection
  connection.release();
});

// Close the connection pool when the application exits
process.on('SIGINT', () => {
  pool.end((err) => {
    if (err) console.error(err);
    process.exit(0);
  });
});

Replace the placeholder values in the pool object with your MySQL database details.

Step 4: Run the Node.js Script

Save the changes to app.js and run the script using the following command:

node app.js

If everything is set up correctly, you should see the message “Connected to MySQL database!” in the console.

Congratulations! You’ve successfully created a connection between Node.js and MySQL. You can now use this connection to perform various database operations in your Node.js application

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button