How To Query Sql In Javascript

When building web applications, it’s often essential to interact with databases to retrieve, store, or manipulate data. In this blog post, we will discuss how to query an SQL database using JavaScript. We will focus on using Node.js as our runtime environment and the popular npm package mysql to handle our database communication.

Prerequisites

Before diving into the code, make sure you have the following installed and available on your development environment:

  • Node.js (you can check if it’s installed by typing node -v in your command line)
  • npm (Node.js Package Manager, comes bundled with Node.js)

Setting Up the Project

First, let’s create a new folder for our project and navigate into it:

mkdir sql-query-javascript
cd sql-query-javascript
    

Next, initialize a new Node.js project using npm:

npm init -y
    

This command will create a package.json file in your project directory.

Now let’s install the mysql npm package:

npm install mysql
    

Creating the Database Connection

Create a new JavaScript file called app.js in your project folder, and add the following code to create a connection to your MySQL database:

    const mysql = require('mysql');

    const connection = mysql.createConnection({
        host: 'localhost',
        user: 'your_database_user',
        password: 'your_database_password',
        database: 'your_database_name'
    });

    connection.connect((err) => {
        if (err) throw err;
        console.log('Connected to the database!');
    });
    

Make sure to replace the placeholders with your actual database credentials.

Performing a Simple SQL Query

With the connection established, we can now perform an SQL query. Let’s say we have a table called users and we want to fetch all records from it. Add the following code to your app.js file:

    connection.query('SELECT * FROM users', (err, results, fields) => {
        if (err) throw err;
        console.log(results);
    });

    connection.end();
    

This code will execute the SQL query SELECT * FROM users and log the results to the console. connection.end() is called to close the connection after the query is done.

Handling Query Parameters

Let’s say we want to fetch a specific user based on their email. We can use placeholders to avoid SQL injection attacks. Here’s how we can do it:

    const userEmail = '[email protected]';

    connection.query('SELECT * FROM users WHERE email = ?', [userEmail], (err, results, fields) => {
        if (err) throw err;
        console.log(results);
    });

    connection.end();
    

The ? symbol is used as a placeholder for the email parameter, which we pass as an array in the second argument of the connection.query() function. This approach helps prevent SQL injection attacks.

Conclusion

In this blog post, we’ve learned how to query an SQL database using JavaScript and Node.js. We discussed setting up a project with Node.js and npm, connecting to a MySQL database using the mysql package, and executing SQL queries with parameterized input. This is a great starting point for building web applications that need to interact with databases.