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

2022-02-17 15:44 更新

要正常关闭数据库连接,请在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.'); });
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号