1

I recently migrated a node.js project from mysqljs to mysql2 (https://www.npmjs.com/package/mysql2) because it had some additional feature that I need. For my database calls, I am exporting a connection that was created by running mysql.createConnection({CONFIG}) that is then imported by other files and then queries are executed using the execute command.

Previous to my transition, in the file where I set up my database connection I had this:

const mysql = require("mysql2");
const dbConfig = require("../config/db.config");

const connection = mysql.createConnection({
    host: dbConfig.HOST,
    user: dbConfig.USER,
    password: dbConfig.PASSWORD,
    database: dbConfig.DB,
    port: dbConfig.PORT
});

connection.connect(error => {
    if (error) throw error;
    console.log("DB connect")
});

module.exports = connection;

My code runs fun without the connection.connect function. Does removing it have any impact on performance, or does mysql2 maintain an open connection regardless or is the creation of the connection negligible? Is it better to keep this line prior to the export or remove it?

Bneac
  • 69
  • 1
  • 10

1 Answers1

1

If you look into the source here, you will see that calling createConnection already performs a handshake with the DB and the connect method is used just to pass any errors that might have occurred when you tried to create the connection. The createConnection method doesn't throw or accepts an error calback. So I would suggest it is safer to keep calling it when creating your connection.

Fcmam5
  • 4,888
  • 1
  • 16
  • 33
px1mp
  • 5,212
  • 1
  • 18
  • 10