Selecting Data from MySQL using Node.js: Mastering Specific and Wildcard Queries

Learn how to efficiently retrieve data from a MySQL database using Node.js. This tutorial demonstrates techniques for selecting single records using `WHERE` clauses and retrieving multiple records using wildcard characters (`%`, `_`), providing practical examples and best practices for building robust data retrieval mechanisms.



Selecting Data from MySQL Using Node.js: Specific and Wildcard Queries

Introduction

This tutorial demonstrates how to retrieve specific data from a MySQL database using Node.js. We'll cover selecting a single record using a `WHERE` clause and selecting multiple records using wildcard characters in the `WHERE` clause.

Prerequisites

Make sure you have:

  • Node.js and npm installed.
  • MySQL server running.
  • MySQL Connector/Node.js installed (`npm install mysql`).
  • A database named `tutorialsarena`.
  • A table named `employees` with columns `id`, `name`, `age`, and `city`.

Selecting a Specific Record

This example retrieves a single employee record based on the employee ID using a `WHERE` clause:

Selecting a Specific Record

const mysql = require('mysql');
const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "your_password", // Replace with your password
  database: "tutorialsarena"
});

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM employees WHERE id = '1'", function (err, result) {
    if (err) throw err;
    console.log(result); 
  });
});

Save this code as `selectwhere.js` and run it from your terminal using `node selectwhere.js`.

Selecting Records Using Wildcards

This example uses wildcard characters to select multiple employees whose city starts with "A":

Selecting with Wildcards

const mysql = require('mysql');
// ... (connection details as above) ...

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM employees WHERE city LIKE 'A%'", function (err, result) {
    if (err) throw err;
    console.log(result);
  });
});

Save this as `selectwildcard.js` and run it using `node selectwildcard.js`.

Conclusion

This tutorial demonstrates basic data retrieval techniques from MySQL using Node.js. Remember to always handle potential errors and use parameterized queries (not shown in these examples) to prevent SQL injection vulnerabilities for improved security.