expressjs
  1. expressjs-querying-databases

ExpressJS Querying Databases

ExpressJS provides various tools and technologies to interact with different types of databases. In this article, we will look at how to query databases in ExpressJS.

Syntax

database.query('SELECT * FROM table_name', (err, result) => {
   if(err) throw err;
   console.log(result);
});

Example

const express = require('express');
const mysql = require('mysql');

const app = express();

const db = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

db.connect((err) => {
  if(err) throw err;
  console.log('MySQL Connected!');
});

app.get('/users', (req, res) => {
  db.query('SELECT * FROM users', (err, rows) => {
    if(err) throw err;
    console.log('Data received from Db:\n');
    console.log(rows);
    res.send(rows);
  });
});

app.listen(3000, () => {
 console.log('Server started on port 3000');
});

Output

The output of the above code will be a list of all the rows with their respective columns in JSON format.

Explanation

In the above example, we have created a connection to the database using the mysql package and created an endpoint /users. When a user hits this endpoint, a query is performed by using the db.query() method. This method takes two arguments, the first one is the SQL query and the second one is a callback function that is called when the query is executed.

If there is any error in the query execution, the err parameter will be set to an error object and the rows parameter will be set to null. If there is no error, the rows parameter will contain an array of rows returned by the query.

Use

Querying databases in ExpressJS is used to retrieve data from a database and display it on the web page. This data can be displayed in various formats like JSON, XML, or HTML.

Important Points

  • Always use parameterized queries to avoid SQL injection attacks.
  • Use connection pooling to improve the performance of the database.
  • Close the database connection once the query execution is finished.

Summary

In this article, we have discussed how to query databases in ExpressJS. We have looked at the syntax, example, output, explanation, use, and important points related to querying databases in ExpressJS.

Published on: