在Node.js中关闭与MySQL数据库的连接通常需要使用MySQL官方提供的Node.js驱动程序(如mysql2或其他)。以下是一个简单的例子,演示如何关闭MySQL数据库连接:
const mysql = require('mysql2');

// 创建数据库连接
const connection = mysql.createConnection({
  host: 'your_host',
  user: 'your_user',
  password: 'your_password',
  database: 'your_database'
});

// 连接到数据库
connection.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL: ' + err.stack);
    return;
  }
  console.log('Connected to MySQL as id ' + connection.threadId);
});

// 在此处执行数据库操作...

// 关闭数据库连接
connection.end((err) => {
  if (err) {
    console.error('Error closing MySQL connection: ' + err.stack);
    return;
  }
  console.log('MySQL connection closed.');
});

在上面的例子中,首先通过mysql.createConnection创建了一个数据库连接对象,然后通过connection.connect连接到数据库。接下来,您可以在此执行与数据库相关的操作。最后,通过connection.end关闭数据库连接。

请注意,这只是一个简单的例子,实际上您可能会使用连接池(connection pool)来管理数据库连接,这样可以更有效地重用连接。如果您正在使用mysql2库,可以考虑使用mysql2.createPool来创建连接池。


转载请注明出处:http://www.zyzy.cn/article/detail/8034/MySQL