What does createConnection() and connect() method do in NodeJS MySql module?

This is how we connect our NodeJS app with Mysql database using MySQL module:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to database:', err);
    return;
  }
  console.log('Connected to database!');
});

I understand we need to call both createConnection() and connect() to make a connection to the database.

However, I want to understand the individual role of the createConnection() and connect() methods.

  • What does createConnection() do?
  • What does connect() do?