
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query Data from Table Using Node
In this article, we will see how to select or query the data from a database based on different table fields and columns.
Before proceeding, please check the following steps are already executed −
mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql
The above steps are for installing the Node - mysql dependecy in the project folder.
Select Data from Table Using Node
Create a new file with the following name – app.js
Copy and Paste the following code snippet in this file.
Now, run the following command to check the output of the above program.
>> node app.js
Example
// Checking the MySQL dependency – if exists var mysql = require('mysql'); // Creating connection with the mysql database var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) console.log("Unable to connect to DB ", err); con.query("SELECT * FROM students", function (err, result, fields) { if (err) throw err; console.log(result); }); });
Output
It will return all the records present in the students table: [ RowDataPacket { id: 1, name: 'John', address: 'Delhi'}, RowDataPacket { id: 2, name: 'Pete', address: 'Mumbai'}, RowDataPacket { id: 3, name: 'Amy', address: 'Hyderabad'}, RowDataPacket { id: 4, name: 'Hannah', address: 'Mumbai'}, RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]
Querying Data from Table Using Node
The following code snippet gives us an example how we can use SQL queries to query and select data from Node.
Example
// Checking the MySQL dependency – if exists var mysql = require('mysql'); // Creating connection with the mysql database var con = mysql.createConnection({ host: "localhost", user: "yourusername", password: "yourpassword", database: "mydb" }); con.connect(function(err) { if (err) console.log("Unable to connect to DB ", err); con.query("SELECT * FROM student where address='Delhi'; ", function (err, result, fields) { if (err) throw err; console.log(result); }); });
Output
It will return result based on our filter −
[ RowDataPacket { id: 1, name: 'John', address: 'Delhi'}, RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]
Advertisements