DEV Community

Nikhil Soman Sahu
Nikhil Soman Sahu

Posted on

How to close a MySQL connection in Node js?

In Node.js, to close a MySQL connection, you need to use the appropriate method provided by the MySQL **driver **you are using.

Here's an example using the popular mysql package:

`const mysql = require('mysql');

// Create a MySQL connection
const connection = mysql.createConnection({
  host: 'your_host',
  user: 'your_user',
  password: 'your_password',
  database: 'your_database'
});

// Connect to the MySQL server
connection.connect((error) => {
  if (error) {
    console.error('Error connecting to MySQL:', error);
    return;
  }

  console.log('Connected to MySQL server.');

  // Perform database operations...

  // Close the MySQL connection
  connection.end((error) => {
    if (error) {
      console.error('Error closing MySQL connection:', error);
      return;
    }

    console.log('MySQL connection closed.');
  });
});
Enter fullscreen mode Exit fullscreen mode

`
In the code above, we first create a MySQL connection using the mysql.createConnection() method, providing the necessary connection details. Then, we use the connection.connect() method to establish a connection to the MySQL server. Inside the callback function of connection.connect(), you can perform your desired database operations.

To close the connection, we call connection.end() and provide a callback function. Inside the callback, you can handle any errors that may occur during the closing process. If successful, the callback will be executed, indicating that the MySQL connection has been closed.

Make sure to replace 'your_host', 'your_user', 'your_password', and 'your_database' with your actual MySQL connection details.

Note that there are other MySQL libraries available for Node.js, such as mysql2 and knex, which may have slightly different syntax for closing connections. Always refer to the specific documentation of the library you are using for the most accurate instructions.

Top comments (1)

Collapse
 
melroy89 profile image
Melroy van den Berg

Avoid using mysql, since that package is not maintained anymore. Instead use: mysql2.