Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 theMySQL **driver **you are using.

Here's an example using the popular mysql package:

`const mysql = require('mysql');// Create a MySQL connectionconst connection = mysql.createConnection({  host: 'your_host',  user: 'your_user',  password: 'your_password',  database: 'your_database'});// Connect to the MySQL serverconnection.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 modeExit fullscreen mode

`
In the code above, we first create a MySQL connection using themysql.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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
melroy89 profile image
Melroy van den Berg
Software Engineer & DevOps Architect. Open-source lover. Blogger.
  • Location
    Netherlands
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer
  • Location
    Banglore
  • Work
    Software Developer
  • Joined

More fromNikhil Soman Sahu

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp