Node js MySQL Select

To select data from table using Node.js, SELECT command is used. For this first we make a connection to the database, then write select query to select data from table.

Syntax

SELECT [Fields] FROM Tablename [WHERE CLAUSE] [LIMIT];

The fields can be either single field name or multiple fields name, the 'WHERE CLAUSE' and 'LIMIT' are optional. The where clause is used to set the condition and limit is used to limited the result rows.

Example

In the given example, we have fetched the all records of 'department' table.

var mysql = require("mysql");
var con = mysql.createConnection({
   host: "hostname",
   user: "username",
   password: "password",
   database: "database"
});

con.connect(function(error){
    if(error) {
        console.log('Error establishing connection to db');
        return;
    }
    console.log('Connection Established'); 
    var selectdata = "Select * FROM department";
    con.query(selectdata, function (error, data) {  
    if(error) { 
        throw(error);
    }  
    console.log("Selected Data are -");  
    console.log(data);  
    });  
});

Open cmd and run the above file as -

nodejs mysql select data


Read more articles


General Knowledge



Learn Popular Language