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 Others

Node.js Connect to MySQL Database

Learn to use the mysql.createConnection method to connect to MySQL database in Node.js through a sample Node.js program.

Node.js Connect to MySQL Database

Node.js provides a module to connect to MySQL database and perform MySQL operations.

The following is a step-by-step guide to connecting to MySQL database using an example.

  • Steps1: Ensure that MySQL is correctly configured. Collect information about the IP address, username, and password.

Steps2: Include the mysql module in your node.js program.

// Import the mysql module
var mysql = require('mysql'); 
 
// Create a connection variable with the required details
var con = mysql.createConnection({ 
  host: "localhost", // IP address of the server running mysql
  user: "arjun", // Username for mysql database
  password: "password" // Corresponding password
 }); 
 
// Connect to the database.
con.connect(function(err) { 
  if (err) throw err; 
  console.log("Connected!"); 
 });
$ node connectToMySQL.js Connected!

Conclusion:

In this Node.js tutorial – Node.js MySQL – we learned how to use the Node.js MySQL module with the help of a Node.js example program-> createConnectionMethod to connect to MySQL database.