How To Query A Database In Javascript

In today’s world, data storage and retrieval have become an essential part of web applications. If you are a JavaScript developer, you might be wondering how you can interact with databases to store, retrieve, and manipulate data. In this blog post, we will learn how to query a database using JavaScript.

Prerequisites

In order to follow along with this tutorial, you will need:

  • Basic knowledge of JavaScript
  • A database to interact with (We’ll be using MySQL in this example)
  • Node.js installed on your system

Setting up the Database

Before we begin writing JavaScript code, let’s set up our database. For this tutorial, we will be using MySQL. If you don’t have MySQL installed, you can download it from here.

After setting up MySQL, create a new database and table with the following SQL query:

CREATE DATABASE sample_db;
USE sample_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(50) NOT NULL UNIQUE
);
    

Setting up Node.js and MySQL Connector

To interact with MySQL using JavaScript, we’ll be using the Node.js runtime environment. Start by creating a new directory for your project and navigate to it using the terminal or command prompt.

Initialize a new Node.js project by running:

npm init -y
    

This will generate a package.json file in your project directory.

Next, install the MySQL connector package by running:

npm install mysql
    

Connecting to the Database

Create a new file named index.js in your project directory and add the following code to connect to the database:

const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'sample_db'
});

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

Make sure to replace your_password with your MySQL root password.

Querying the Database

To query the database, add the following code to your index.js file:

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

This code will query the users table and log the results to the console. To execute the file, run:

node index.js
    

Since we don’t have any data in our users table yet, the output should be an empty array. To insert data into the table, you can modify the query:

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

connection.query('INSERT INTO users SET ?', newUser, (err, res) => {
    if (err) throw err;
    console.log('User inserted:', res.insertId);
});
    

Now, when you run the script, a new user will be inserted into the users table, and you should see the inserted user’s ID in the console output.

Conclusion

In this tutorial, we learned how to query a database using JavaScript and Node.js. We set up a MySQL database, connected to it using the MySQL connector package, and executed SQL queries to retrieve and insert data. This basic knowledge will help you build more complex web applications that interact with databases.