Node.js MySQL SELECT FROM Query Examples - Tutorial Kart

[Pages:10]Node.js MySQL SELECT FROM Query Examples

Learn Node.js MySQL SELECT FROM query to access data of a MysQL Table.

Node.js MySQL SELECT FROM query

MySQL SELECT Query is used to select some of the records (with some of their properties if required) of a table.

In this Node.js Tutorial, we shall learn to access data of a table using following Node.js examples

Example to MySQL SELECT FROM query Example to select only some of the columns Example to use Result Object of MySQL SELECT FROM query Example to use Fields Object of MySQL SELECT FROM query

We shall use the following MySQL Table, in the examples of this section [DATABASE : studentsDB, Table: studends]

studentsDB.students table

mysql> select * from students; +----------+-------+-------+ | name | rollno | mmayrkssql|> select * from students; ++--------------------++----------------+-------+ +-------+ ||Jnohanme || roll1no| | marks | 7|+4A-r|-j-u-n----|--+-2--|-----+-------+ 7|4J|ohn | 1 | 74 | |7|7PAr|arsjuannth| |2 | 734|| ||APdraarssahnt|h | 34 || 77 | 78 | ||RAadjaarsh| | 4 5| |78 | 9||4SRa|ai ja || 5 | 694| | 84 || Sai | 6 | 84 | |5|4RRo|ossss | |7 | 574|| ||MMoonniciaca || 8 |8 8|6 | 86 | ||LLeeee | 9| | 998 || 9|8B|ruce | 10 | 92 | | Bruce | 10 | 9|2S|ukumar | 11 | 99 | |9+9S-u|-k--u-m--a-r--|+---1-1--|--+-------+ +1-1--r-o-w--s--i-n+-s-e--t-(-0--.01 sec) +-------+ 11 rows in set (0.01 sec)

Example to MySQL SELECT FROM query

selectFromTable.js Simple example to MySQL SELECT FROM query

// Node.js MySQL SELECT FROM query Example // include mysql module v/a/rNmoydseq.jls=MySQL SELECT FROM query Example require('mysql'); // include mysql module

/v/acrrmeaytseqla=croenqnueircet(io'mnysql'); variable with the required details vm/a/yrsccqreol.anctr=eeaatecCoonnnneeccttioion variable with the required details nv(a{r con = mysql.createConnection({

host: "localhost", // ip haodsdtr:es"lsocoaflhsoesrvt"e,r// ip address of server running mysql rununseinrg: "mayrjsuqnl", // user name to your mysql database

user: "arjun", // user napmaesstwooyrodu: r"pmaysssqwlord", // corresponding password dadtaatbaabsaese: "studentsDB" // use the specified database

password: "}p)a;ssword", // c orresponding password //damtakbeasteo:connection to the database. "studentsDB" // use tchoens.cpoencnifeiecdt(dfuantacbtiaosne(err) { })i;f (err) throw err;

///m/ aifkecotnonceocntinoencitsiosnuccessful tcoocnto.hcneo.qndunaeetracybt((a"fSsueEn.LcEtCioTn(* FROM students", function (err, result, fields) { err)/{/ if any error while executing above query, throw error

if (err) throw err; // ifif (ceorrn)ntehcrtoiown eisrr; succ//esifsftuhlere is no error, you have the result con.query("SELECT * FROcMonsstouldee.lnotgs("r,esult); ffuien}ldc)s;t)io{n (err, result, }//);if any error while executing above query, throw error

if (err) throw err; // if there is no error, you have the result $ ncoodnesole.log(result); se}l)e;ctFromTable.js }[ )R;owDataPacket { name: 'John', rollno: 1, marks: 74 },

$Rnowo dDeatasPeal cekcettF{ro m T a b l e . j s n[aRmoew: 'DAarjtuanP',arcokllenot :{ name: 'John', rollno: 1, marks: 74 }, 2, marks: 74 },

RRoowwDDataatPaaPckaectk{et { name: 'Arjun', rollno: 2, marks: 74 }, nroalRmlnoeow:: 'D3P,raamtsaaaPrnkatshc:'k,7e7t { name: 'Prasanth', rollno: 3, marks: 77 }, },RowDataPacket { name: 'Adarsh', rollno: 4, marks: 78 },

RowDataPacket { naRmoew: 'DAadtaarsPha',cket { name: 'Raja', rollno: 5, marks: 94 }, rolRlnoow: D4,amtaaPrkasc:k7e8t { name: 'Sai', rollno: 6, marks: 84 }, },

RRoowwDDataatPaaPckaectk{et { name: 'Ross', rollno: 7, marks: 54 }, naRmoew: 'DRaajtaa',Praocllkneot: { name: 'Monica', rollno: 8, marks: 86 }, 5, marks: 94 },

RRoowwDDataatPaaPckaectk{et { name: 'Lee', rollno: 9, marks: 98 }, nmaaRmrokesw::'DS8aa4it'},a,rPoallcnkoe:t6,{ name: 'Bruce', rollno: 10, marks: 92 },

RRoowwDDataatPaaPckaectk{et { name: 'Sukumar', rollno: 11, marks: 99 } ] name: 'Ross', rollno: 7, marks: 54 },

RowDataPacket { name: 'Monica',

Er}o,xllnaom: 8p, mlearktso: 8s6elect only some of the columns

RowDataPacket { name: 'Lee', rollno: 9,

We shall select only two columns, name and marks

// Node.js MySQL SELECT FROM query Example // include mysql module v/a/rNmoydseq.jls=MySQL SELECT FROM query Example require('mysql'); // include mysql module

/v/acrrmeaytseqla=croenqnueircet(io'mnysql'); variable with the required details vm/a/yrsccqreol.anctr=eeaatecCoonnnneeccttioion variable with the required details nv(a{r con = mysql.createConnection({

host: "localhost", // ip haodsdtr:es"lsocoaflhsoesrvt"e,r// ip address of server running mysql rununseinrg: "mayrjsuqnl", // user name to your mysql database

user: "arjun", // user napmaesstwooyrodu: r"pmaysssqwlord", // corresponding password dadtaatbaabsaese: "studentsDB" // use the specified database

password: "}p)a;ssword", // c orresponding password //damtakbeasteo:connection to the database. "studentsDB" // use tchoens.cpoencnifeiecdt(dfuantacbtiaosne(err) { })i;f (err) throw err;

///m/ aifkecotnonceocntinoencitsiosnuccessful tcoocnto.hcneo.qndunaeetracybt((a"fSsueEn.LcEtCioTn(name,marks FROM students", function (err, result, fields) { err)/{/ if any error while executing above query, throw error

if (err) throw err; // ifif (ceorrn)ntehcrtoiown eisrr; succ//esifsftuhlere is no error, you have the result c on.query("SELECT namceo,nmsaorlkes.loFgR(OreMsult); s(etu}rrd),;ernetssu"l,t,fufniecldtiso)n{ }//);if any error while executing above query, throw error

if (err) throw err; // if there is no error, you have the result $ ncoodnesole.log(result); se}l)e;ctColumns.js }[ )R;owDataPacket { name: 'John', marks: 74 },

$Rnowo dDeatasPeal cekcettC{o l u m n s .j s n[aRmoew: 'DAarjtuanP',amckaerkts:{ name: 'John', marks: 74 }, 74 },

RRoowwDDataatPaaPckaectk{et { name: 'Arjun', marks: 74 }, nmaaRmrokesw::'DP7ra7ats}aa,Pnathc'k,et { name: 'Prasanth', marks: 77 },

RRoowwDDataatPaaPckaectk{et { name: 'Adarsh', marks: 78 }, name: 'Adarsh', maRroksw:D7a8t}a,Packet { name: 'Raja', marks: 94 },

RRoowwDDataatPaaPckaectk{et { name: 'Sai', marks: 84 }, name: 'Raja', marks: 94R}o,wDataPacket { name: 'Ross', marks: 54 }, naRRmoowew:D'DaStaaaitP',aamPckaaecrtkk{se:t { name: 'Monica', marks: 86 }, 84R}o,wDataPacket { name: 'Lee', marks: 98 }, naRRmoowew:D'DaRtaoatsPasa'Pc,kamectak{rekts:{ name: 'Bruce', marks: 92 }, 54R}o,wDataPacket { name: 'Sukumar', marks: 99 } ]

RowDataPacket { name: 'Monica', marks: 86 },

RowDataPacket { name: 'Lee', marks:

Example to use Result Object of MySQL SELECT FROM query

You may access rows using index and columns using dot operator.

selectUseResultObject.js - Access rows and column data of result object

// Node.js MySQL SELECT FROM query Example // include mysql module v/a/rNmoydseq.jls=MySQL SELECT FROM query Example require('mysql'); // include mysql module

/v/acrrmeaytseqla=croenqnueircet(io'mnysql'); variable with the required details vm/a/yrsccqreol.anctr=eeaatecCoonnnneeccttioion variable with the required details nv(a{r con = mysql.createConnection({

host: "localhost", // ip haodsdtr:es"lsocoaflhsoesrvt"e,r// ip address of server running mysql rununseinrg: "mayrjsuqnl", // user name to your mysql database

user: "arjun", // user napmaesstwooyrodu: r"pmaysssqwlord", // corresponding password dadtaatbaabsaese: "studentsDB" // use the specified database

password: "}p)a;ssword", // c orresponding password //damtakbeasteo:connection to the database. "studentsDB" // use tchoens.cpoencnifeiecdt(dfuantacbtiaosne(err) { })i;f (err) throw err;

///m/ aifkecotnonceocntinoencitsiosnuccessful tcoocnto.hcneo.qndunaeetracybt((a"fSsueEn.LcEtCioTn(* FROM students", function (err, result, fields) { err)/{/ if any error while executing above query, throw error

if (err) throw err; // ifif (ceorrn)ntehcrtoiown eisrr; succ//esifsftuhlere is no error, you have the result con.query("SELECT * FRO/M/ istteuradteentfso"r, all the rows in result ffuienldcOstb)ioj{enc(te.krre,yrse(sruelstu,lt).forEach(function(key) { // if vaanryreorwro=r wrehsiluelt[key]; executing above query, t hrowc oenrrsoorle.log(row.name)

if})(;err) throw err; // if there is no error, yo}u);have the result }//);iterate for all the rows in result Objec t .keys(result ).for Each(function(key) {

var row = result[key]; $ node csoenlescotlUe.sloegR(ersouwl.tnOabmjec)t .}js); Jo}h);n }A)r;jun Prasanth Adarsh Raja Sai Ross Monica Lee Bruce Sukumar

$ node selectUseResultObject.js

John

Arjun

P ra s a n t h

A d a rs h

Raja

Sai

Ross

Monica

Lee

Bruce

Sukumar

Example to use Fields Object of MySQL SELECT FROM query

Fields contain information about columns of table. Each field contains all information about a column.

selectUseFieldsObject.js - Example for the usage of fields

// Node.js MySQL SELECT FROM query Example // include mysql module var mysql = require('mysql');

// create a connection variable with the required details var con = mysql.c reat eConnec t io n({

host: "localhost", // ip address of server running mysql

user: "arjun", // user name to your mysql database

password: "password", // c orresponding password

database: "studentsDB" // use the specified database });

// make to connection to the database. c on.c onnec t (func t ion( err) {

if (err) throw err; // if connection is suc c essful con.query("SELECT * FROM students", function (err, result, fields) { // if any error while executing above query, throw error

if (err) throw err; // if there is no error, you have the fields

// Node.js MySQL SELECT FROM query Example // include mysql module var mysql = require('mysql');

// create a connection variable with the required details var con = mysql.createConnection({

host: "localhost", // ip address of server running mysql user: "arjun", // user name to your mysql database password: "password", // corresponding password database: "studentsDB" // use the specified database });

// make to connection to the database. con.connect(function(err) {

if (err) throw err; // if connection is successful con.query("SELECT * FROM students", function (err, result, fields) {

// if any error while executing above query, throw error if (err) throw err; // if there is no error, you have the fields object // iterate for all the rows in fields object Object.keys(fields).forEach(function(key) {

var field = fields[key]; c onsole.log(field) }); }); });

$ node selectUseFieldsObject. js FieldPacket {

catalog: 'def', $dbn:o 'dsetusdeenl etscDt UBs',e Fi e l d s O b j e ct .j s Ftiaebl dleP: a'sctkuedten{ts', orgTable: 'stcuadteanltosg',: 'def', nodargbmN:ea:'ms'tneua:dm'neean',mtseD',B', cthaabrsl et:N'rs:t3u3d,e n t s ', length: 150, toyprge:Ta25b3le, : 'students', flnaagsm:e0:, 'name', decimals: 0, doerfgauNlta:muned: e'fninaemd,e ', zcehroaFrisll:e tfaNlsre: ,33, protocol41: true } FiellednPagctkhe:t 1{50, cdtabyt:apl'eosgt:u:2d'5dene3ft,'s,DB', tfalbaleg:s ':s t0u,dents ', orgTable: 'stduedceinmtsa',ls: 0, ndaemfea:u'lrto:llnuon',d e f i n e d , orgName: 'rollno', czhearsoeFtiNllr:: f6a3l,se,

zeroFill: false, protocol41: true } FieldPacket { catalog: 'def', db: 'studentsDB', table: 'students', orgTable: 'students', name: 'rollno', orgName: 'rollno', charsetNr: 63, length: 11, type: 3, flags: 0, decimals: 0, default: undefined, zeroFill: false, protocol41: true } FieldPacket { catalog: 'def', db: 'studentsDB', table: 'students', orgTable: 'students', name: 'marks', orgName: 'marks', charsetNr: 63, length: 11, type: 3, flags: 0, decimals: 0, default: undefined, zeroFill: false, protocol41: true }

You may use the elements of a field object using dot operator. Example field.catalog, field.name, field.type, etc.

Conclusion :

In this Node.js Tutorial ? Node.js MySQL ? Node.js MySQL SELECT FROM query, we have learnt to fetch records of table from MySQL database, and to use result object and fields object.

Node.js

Node.js Tutorial

Get Started W ith Node.js

Install Node.js Ubuntu Linux

Install Node.js Windows

Node.js - Basic Example Node.js - Command Line Arguments Node.js - Modules Node.js - Create a module Node.js - Add new functions to Module Node.js - Override functions of Module Node.js - Callback Function Node.js - forEach

E xp re s s .j s

Express.js Tutorial What is Express.js? Express.js Application Example Install Express.js Express.js Routes Express.js Middleware Express.js Router

Node.js Buffers

Node.js Buffer - Create, Write, Read Node.js Buffer - Length Node.js - Convert JSON to Buffer Node.js - Array to Buffer

Node.js HTTP

Node.js - Create HTTP Web Server Node.js - Redirect URL

Node.js MySQL

Node.js MySQL Node.js MySQL - Connect to MySQL Database Node.js MySQL - SELECT FROM Node.js MySQL - SELECT WHERE Node.js MySQL - ORDER BY Node.js MySQL - INSERT INTO Node.js MySQL - UPDATE Node.js MySQL - DELETE Node.js MySQL - Result Object

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download