English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js MySQL

Node.js MySQL is one of the external libraries of Node.js. It can help Node.js developers connect to the MySQL database and execute MySQL queries.

We will learn how to install the MySQL module in Node.js using npm, and use SQL statements with clear examples.

Node.js MySQL

Below is a quick overview of the topics related to Node.js MySQL that we will learn

  • Install Node.js MySQL module

  • Node.js MySQL Connect database

  • MySQL query in Node.js

    • MySQL SELECT FROM table query

    • MySQL INSERT INTO table query – Node.js MySQL tutorial for inserting records into a table

    • MySQL WHERE clause and SELECT query

    • MySQL ORDER BY clause and SELECT Query – Node.js MySQL tutorial can sort records in order according to one of the attributes of the table records.

    • MySQL UPDATE table query

    • MySQL DELETE record query

    • Usage of MySQL result object in callback function

    • Usage of MySQL Fields object in callback function

    • Usage of MySQL error object in callback function

Install MySQL in Node.js

Since Node.js MySQL is an external module, it can be installed using NPM (Node Package Manager).

Run the following command in the terminal or command prompt to install the MySQL module and use it in the Node.js program.

$ npm install mysql

After successful installation, you can declare its usage through the require statement and use the MySQL module in the node.js program, as shown below.

var mysql = require('mysql');

Note– If the MySQL module is not installed but the MySQL module is used in the Node.js program, you may receiveError: Module 'mysql' not found.

Create a connection to the MySQL database

To create a connection variable using the IP address (the server running MySQL services), username, and password (the user with access to the MySQL database), the following example is provided:

var con = mysql.createConnection({ 
  host: "localhost", // The IP address of the server running mysql
  user: "arjun", // The username for the mysql database
  password: "password", // The corresponding password
  database: "studentsDB" // Use the database query context
 });

Select from the query

The MySQL SELECT Query is used to select certain records from the table (and some properties if necessary).

con.query("SELECT * FROM studentsDB.students", function (err, result, fields) { 
    // If any errors occur during the execution of the above query, throw an error
    if (err) throw err; 
    // If there are no errors, you will get the result
    console.log(result); 
 });

Conclusion:

In this Node.js tutorial, we learned how to install the MySQL module in Node.js using npm/Software Package.