In this tutorial you will learn about the Nodejs MySQL Select Records and its application with practical example.
Node.js MySQL Select Records
Records can be selected from MySQL Table simply by using “SELECT” statement.
Example :- Let’s select all records from “employees” table under “nodemysql” database.
Step 1:- Let’s, create a node_mysql_select_all.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; con.query("SELECT * FROM employees", function (err, result) { if (err) throw err; console.log("W3Adda | Selecting All Record from MySQL Table"); console.log(result); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mysql_select_all.js |
you will see following output on terminal –
Node.js MySQL Select With Where
Example :- Let’s select a record from “employees” table “emp_name” is “Keith”.
Step 1:- Let’s, create a node_mysql_select_single.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var mysql = require('mysql'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "nodemysql" }); con.connect(function(err) { if (err) throw err; con.query("SELECT * FROM employees WHERE emp_name = ? ", ['Keith'], function (err, result) { if (err) throw err; console.log("W3Adda | Selecting All Record from MySQL Table"); console.log(result); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node <strong>node_mysql_select_single</strong>.js |
you will see following output on terminal –