nodejs query database example


To query a database from a Node.js application, you can use a library like mysql2 or pg (which is a PostgreSQL client for Node.js).

Here is an example of how you can use the mysql2 library to connect to a MySQL database, execute a query, and print the results:

const mysql = require('mysql2');

// Create the connection to the database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test',
  password: 'password'

// Execute a query
  'SELECT * FROM users WHERE name = ?',
  (err, results, fields) => {
    console.log(results); // results contains rows returned by the query
    console.log(fields); // fields contains extra meta data about results, if available

// Close the connection

This example queries the users table for all rows where the name column is ‘Alice’, and prints the results to the console.

You can use a similar approach to query a PostgreSQL database using the pg library.