Skip to content
Related Articles

Related Articles

NodeJS MySQL Select from Table
  • Difficulty Level : Medium
  • Last Updated : 08 Feb, 2021

Introduction: Learn about Selecting data from MySQL database using node.js. We are going to use standard SELECT FROM SQL Query.

Syntax:

SELECT [column] FROM [table_name]

Example:

1) SELECT * FROM customers
selecting all columns from customers table.

2) SELECT name, address FROM customers

SQL users Table Preview:



Example 1: select all columns from users table

index.js




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // This query will be used to select columns
    let query = 'SELECT * FROM users';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Output:

Example 2: select name column from users table

index.js




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // notice the name column below
    let query = 'SELECT name FROM users';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Output:


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :