How to use MySQL Database with NodeJS App

MySQL is the most popular database system. In this tutorial we will describe the steps required to use MySQL database with NodeJS app.

Install MySQL Driver

We need to install MySQL driver to use the MySQL database with NodeJS app. To install it, please run the following command in project folder.

npm install mysql

Adding the MySQL Module in NodeJS App

Now we can use the mysql module in NodeJS app using:

var mysql = require('mysql');

Creating Connection of MySQL Database with NodeJS App

var mysql = require('mysql'); //adding the mysql module

var conn = mysql.createConnection({
  host: "localhost",
  user: "database username",
  password: "database password"
});

//checking the connection

conn.connect(function(err) {
  if (err){
     throw err;
     console.log(err);
  }else{
     console.log("Connected!");
  }
});

Insert Into Table:

var sql = "INSERT INTO notes (title, content) VALUES ('Note Title Here ...', 'Note Description Here ...')";
conn.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
});

Selecting Record From Table

var sql = "SELECT * FROM notes";
con.query(sql, function (err, result, fields) {
    if (err) throw err;
    console.log(result);
});

Conditional Select From Table

var sql = "SELECT * FROM notes WHERE title= 'Park Lane 38'";
conn.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result);
});

Delete From Table

var sql = "DELETE FROM notes WHERE title = 'Mountain 21'";
conn.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Number of rows deleted: " + result.affectedRows);
});

Update Record

var sql = "UPDATE notes SET address = 'Canyon 123' WHERE address = 'Valley 345'";
conn.query(sql, function (err, result) {
    if (err) throw err;
    console.log(result.affectedRows + " record(s) updated.");
});

Leave a Comment

Your email address will not be published. Required fields are marked *