关闭 Node.js 与 MySQL 数据库连接

aiofo2022-08-03  174

要正常关闭数据库连接,请在connection对象上调用end()方法。

end()方法确保在数据库连接关闭之前始终执行所有剩余的查询。

connection.end(function(err) {  if (err) {    return console.log('error:' + err.message);
  }  console.log('Close the database connection.');
});
SQL

要立即强制连接,可以使用destroy()方法。 destroy()方法保证不会再为连接触发回调或事件。

connection.destroy();
Js
请注意,destroy()方法不会像end()方法那样采取任何回调参数。

到目前为止,整个connect.js文件的完整代码如下 -

let mysql = require('mysql');let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'todoapp'});

connection.connect(function(err) {  if (err) {    return console.error('error: ' + err.message);
  }  console.log('Connected to the MySQL server.');
});//connection.destroy();connection.end(function(err) {  if (err) {    return console.log('error:' + err.message);
  }  console.log('Close the database connection.');
});


转载请注明原文地址:https://www.aiofo.com/read-355.html