Connecting Node.js to MySQL: Establishing a Database Connection

Learn how to establish a robust connection between your Node.js application and a MySQL database. This tutorial provides a step-by-step guide with a clear code example, demonstrating the essential steps for connecting to your MySQL server and verifying a successful connection.



Node.js MySQL Connection

This section explains how to establish a connection between Node.js and a MySQL database.

Prerequisites

  1. Install MySQL: Download and install MySQL from https://www.mysql.com/downloads/
  2. Install MySQL Driver (Node.js): Use npm to install the MySQL driver:
Install MySQL Driver

npm install mysql
            

Creating the Connection

Create a folder named "DBexample". Inside, create a JavaScript file named "connection.js" with the following code:

Connection Code

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "12345" // Remember to replace this with your MySQL root password!
});

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

Important: Replace `"12345"` with your actual MySQL root password.

Run this script using the command node connection.js. If successful, you'll see "Connected!" printed to your console, indicating a successful connection to your MySQL server.

next →

← prev