Node.js – Connect to MySQL Database

In this tutorial, we shall learn to Connect to MySQL database in Node.js using mysql.createConnection method with an example Node.js program.

Node.js can connect to a MySQL server through a MySQL driver package. Once the connection is created, the application can run SQL statements, read returned rows, and handle connection errors from JavaScript code.

connect to MySQL database in Node.js

Before Connecting Node.js to MySQL Database

Before you run the Node.js connection program, make sure these details are ready.

  • MySQL server is installed and running on your computer or remote server.
  • You know the MySQL host name or IP address. For a local database, this is usually localhost.
  • You have a MySQL user name and password with permission to connect.
  • You know the database name if the program must connect to a specific database.
  • The mysql npm package is installed in the same Node.js project folder.

Steps to Connect to MySQL Database via Node.js

Following is a step-by-step guide to connect to MySQL database with an example.

Step 1: Make sure that MySQL is configured properly. Collect the information about IP Address, User Name and Password.

Step 2: In your node.js program, include mysql module.

</>
Copy
var mysql = require(‘mysql‘);

MySQL module has to be installed before it can be used. Otherwise you would get an error.

To install mysql module, refer how to install MySQL in Node.js.

If you are starting with an empty project folder, you can initialize the project and install the dependency as shown below.

</>
Copy
npm init -y
npm install mysql

Step 3: Create a connection variable with IP Address, User Name and Password collected in Step 1.

</>
Copy
var con = mysql.createConnection({
  host: "localhost",    // ip address of server running mysql
  user: "arjun",    // user name to your mysql database
  password: "password"    // corresponding password
});

Step 4: Make a call to connect function using connection variable, that we created in the previous step.

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

Function provided as argument to connect is a callback function. After node.js has tried with connecting to MySQL Database, the callback function is called with the resulting information sent as argument to the callback function.

Node.js MySQL Connection Options

The object passed to mysql.createConnection() contains the details required to reach the MySQL server and authenticate the user.

OptionMeaningExample
hostHostname or IP address of the MySQL server.localhost
userMySQL user name used for authentication.arjun
passwordPassword for the MySQL user.password
databaseDatabase to use after the connection is made.studentsDB
portMySQL server port, when it is different from the default configuration.3306

The database option is optional only when you want to connect to the MySQL server first and choose a database later. For most application queries, include the database name in the connection settings.

Example 1 – Connect to MySQL Database via Node.js

In this example, we will connect to a MySQL instance running in the localhost.

connectToMySQL.js

</>
Copy
// include mysql module
var mysql = require('mysql');

// create a connection variable with the details required
var con = mysql.createConnection({
  host: "localhost",	// ip address of server running mysql
  user: "arjun",	// user name to your mysql database
  password: "password"	// corresponding password
});

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

You may change the host as per your requirements. It could be an IP, or a URL, etc.

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

$ node connectToMySQL.js 
Connected!

Connect Node.js to a Specific MySQL Database

When your queries target a particular database, add the database option in the connection object. This avoids writing the database name before every table name in simple examples.

</>
Copy
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "arjun",
  password: "password",
  database: "studentsDB"
});

con.connect(function (err) {
  if (err) {
    console.error("Connection failed:", err.message);
    return;
  }

  console.log("Connected to studentsDB database.");
});

Verify MySQL Connection with a Simple Query

A successful connection only confirms that Node.js can reach MySQL and authenticate the user. To verify that the selected database is usable, run a small query after connecting.

</>
Copy
con.connect(function (err) {
  if (err) {
    console.error("Connection failed:", err.message);
    return;
  }

  con.query("SELECT DATABASE() AS currentDatabase", function (err, result) {
    if (err) {
      console.error("Query failed:", err.message);
      con.end();
      return;
    }

    console.log(result);
    con.end();
  });
});

If the connection uses database: "studentsDB", the result shows the current database selected for that connection.

[ { currentDatabase: 'studentsDB' } ]

Handle Node.js MySQL Connection Errors Cleanly

During development, throw err is quick for testing, but it stops the program immediately. In application code, it is better to log a clear message and return from the callback.

</>
Copy
con.connect(function (err) {
  if (err) {
    console.error("Unable to connect to MySQL:", err.code);
    console.error(err.message);
    return;
  }

  console.log("Connected!");
});

Common connection errors usually come from wrong credentials, a stopped MySQL server, a wrong host or port, or a database user that does not have permission to connect from the current machine.

Error code or messageLikely causeWhat to check
Cannot find module 'mysql'The mysql package is not installed in the current project.Run npm install mysql in the project folder.
ER_ACCESS_DENIED_ERRORMySQL rejected the user name, password, or host.Check credentials and user permissions.
ECONNREFUSEDNode.js could not reach the MySQL server.Check that MySQL is running and the host/port are correct.
ER_BAD_DB_ERRORThe database name in the connection object does not exist.Create the database or correct the database value.

Close the MySQL Connection in Node.js

After the database work is complete, close the connection using con.end(). This is especially useful in small scripts because it allows the Node.js process to finish cleanly.

</>
Copy
con.end(function (err) {
  if (err) {
    console.error("Error while closing MySQL connection:", err.message);
    return;
  }

  console.log("Connection closed.");
});

Node.js MySQL createConnection and Connection Pooling

The mysql.createConnection() method creates one connection. It is suitable for a simple script or a basic tutorial example. In a server application that handles many requests, a connection pool is usually preferred because it can reuse connections instead of opening a new connection for every request.

For this tutorial, createConnection() keeps the example easy to follow. When you move to a larger Express or API project, review connection pooling before using the database layer in production code.

Node.js MySQL Connection QA Checklist

  • Confirm that the Node.js script is executed from the project folder where mysql is installed.
  • Check that the MySQL server is running before testing con.connect().
  • Verify that host, user, password, database, and port match your MySQL setup.
  • Run a small verification query such as SELECT DATABASE() after connecting.
  • Close the connection with con.end() when the script has finished its database work.

FAQs on Connecting Node.js to MySQL Database

Which method is used to connect Node.js to MySQL database?

The mysql.createConnection() method is used to create a MySQL connection object. Then con.connect() is called to open the connection to the MySQL server.

Why does Node.js show Cannot find module ‘mysql’?

This error means the mysql package is not installed in the current Node.js project, or the script is being run from a different folder. Install it with npm install mysql in the project directory.

Do I need to include the database name in mysql.createConnection?

It is not always required, but it is recommended when your program works with a specific database. Add database: "yourDatabaseName" in the connection object so queries can refer to tables directly.

How do I know if the Node.js MySQL connection is working?

If the callback of con.connect() has no error, the connection has opened successfully. You can also run a small query such as SELECT DATABASE() to confirm that the selected database is available.

Should I use createConnection for a production Node.js API?

createConnection() is fine for simple scripts and learning examples. For an API or web application that serves many requests, use a connection pool so database connections can be reused more efficiently.

Conclusion: Connect Node.js Program to MySQL Database

In this Node.js TutorialNode.js MySQL – Connect to Database, we have learnt to Connect to MySQL database using Node.js MySQL Module -> createConnection method with the help of an example Node.js program. We also reviewed connection settings, database selection, simple verification queries, common connection errors, and when to consider connection pooling.