NodeJs MySql Example

In this node mysql example you will learn how to build nodejs application with mysql database, we need to create a MySql instance in our Node JavaScript code.

To work with MySql database we first need to install MySql module in NodeJs application.

Before executing the following command, make sure you go to the current working folder of your project, like cd d:myproject

npm install mysql

Now add the database reference using require('mysql') and create an instance.

var mysql = require('mysql');

Now set up all database credentials in above MySql instance, so that we can establish the connection to some database and start working with that database from Node JS code.

Create MySql connection in NodeJs

var con = mysql.createConnection({
  host: "localhost",
  user: "username",
  password: "password",  
  database: "mydatabaseName",
  port:"0001",
  multipleStatements: true
});

Instead of hard coding database credential in every file, we can store any information in configuration file and read from there, here is the example of how to read Json config file in Node JS application.

Connect database and fetch data in NodeJs

Now we use the above connection object to fetch data from mysql database.

Notice, in code below we are reading data from MySql using NodeJs code, if there is any error then the method will throw exception, otherwise the result variable will contain the output.

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("select * from tbadminuser", function (err, result)
{
if (err) throw err;
//console.log("Result: " + result);
result.forEach( (row) => {
      console.log(`${row.username} - ${row.password}`);
    });
  });

In above code I am trying fetch all rows from some table, so now I want to loop through all the rows and retrieve each property of each row.

result.forEach( (row) => {
      console.log(`${row.username} - ${row.password}`);
    });

nodejs mysql update example.

Let's look at another example of how to update data in mysql database from node js code

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  let _updateQuery="update tbadminuser" +
  " set password='pass100'" +
  " where username='admin2'";
  con.query(_updateQuery, function (err, result) {
    if (err) throw err;
    console.log("data updated!");    
  });
  con.end();
});

Notice, there is common method con.query(query, function (err, result)), so we can execute any type of query like insert, update, delete, fetch etc. and then the function will have the result or the error details.

You may be intereted to read following posts

 
Node and MySql example
Learn Node application development, free node js framework tutorial with examples.
Node examples | Join JavaScript Course