gpt4 book ai didi

mysql - ExpressJS - 如何正确关闭 MySQL 连接

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:09 25 4
gpt4 key购买 nike

我正在使用 ExpressJS进口 MySQLJS .使用 ExpressJS 作为后端,我有一个名为 /get-candidates 的服务,其中 ExpressJS 尝试从 MySQL 表中获取一些数据并返回给请求者。
我正在寻找一种在将 JSON 返回给请求者之前正确关闭 MySQL 数据库连接的方法。

这是我的 /get-candidates 的样子:

module.exports.getCandidates = function (request, response) {

var mysql = require("mysql");
var connectionSettings = require("../db.conf.json");
var connection = mysql.createConnection(connectionSettings);

connection.connect();

connection.query('SELECT * FROM Candidates', function (err, rows, fields) {
if (err) {
throw err;
} else {
response.json(rows);
}
});

connection.end(); // I don't think the code reaches this part after line 'response.json(rows)'
};

最佳答案

您可以在获取查询结果错误或成功获取记录后关闭连接。

module.exports.getCandidates = function(request, response) {

var mysql = require("mysql");
var connectionSettings = require("../db.conf.json");
var connection = mysql.createConnection(connectionSettings);

connection.connect();

connection.query('SELECT * FROM Candidates', function(err, rows, fields) {

connection.end();

if (err) {
throw err;
} else {
response.json(rows);
}

});


};

关于mysql - ExpressJS - 如何正确关闭 MySQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com