Node.js program for storing data in a MySQL database

In this post, I am going to show an example of a Node.js program to store the data in a MySQL database.

To store data in MySQL using Node.js, you’ll need to follow these steps:

  1. Set Up a MySQL Database: If you haven’t already, you need to have MySQL installed on your system. You should also create a database and a table where you want to store your data. You can use tools like phpMyAdmin or command-line utilities to do this.
  2. Install Required Node.js Packages: You’ll need to install the mysql package, which is a MySQL driver for Node.js. You can install it using npm (Node Package Manager):
    • npm install mysql
  3. Create a Node.js Application: Now, create a Node.js application where you can interact with the MySQL database.
  4. Initialize the MySQL Connection: You need to establish a connection to the MySQL database using your credentials. Here’s an example:
    • const mysql = require('mysql');
      
      const connection = mysql.createConnection({
        host: 'localhost',
        user: 'your_username',
        password: 'your_password',
        database: 'your_database_name'
      });
      
      connection.connect((err) => {
        if (err) {
          console.error('Error connecting to MySQL: ' + err.stack);
          return;
        }
        console.log('Connected to MySQL as id ' + connection.threadId);
      });
      

       

  5. Insert Data into the MySQL Database: To insert data into the database, you can use SQL queries. Here’s an example of how to insert data:
    • const newData = { name: 'John', email: 'john@example.com' };
      
      const insertQuery = 'INSERT INTO your_table_name SET ?';
      
      connection.query(insertQuery, newData, (err, results) => {
        if (err) throw err;
        console.log('Inserted new data with ID:', results.insertId);
      });
      
  6. Retrieve Data from the MySQL Database: To retrieve data, you can use SQL SELECT queries. Here’s an example:
    • const selectQuery = 'SELECT * FROM your_table_name';
      
      connection.query(selectQuery, (err, results) => {
        if (err) throw err;
        console.log('Retrieved data:', results);
      });
      
  7. Close the MySQL Connection:
    • connection.end((err) => {
        if (err) {
          console.error('Error closing the connection: ' + err.stack);
          return;
        }
        console.log('Connection closed.');
      });
      

Replace placeholders like your_username, your_password, your_database_name, your_table_name, and the data you want to insert with your actual information. This is a simple example of showing how to insert and retrieve data in a MySQL database and tables. Additionally, you may want to use asynchronous methods or a connection pool for better performance in a production environment.

Leave a Comment

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

Scroll to Top