我每 5 秒查询一个表并向用户显示。我使用的是mysql 8。应用程序是nodejs。
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: xxxxxx,
database: "test"
});
app.get('/users', (req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query(" select * fron table1; ",function (err, result, fields) {
if (err) throw err;
console.log(result);
if (result.length > 0) {
res.send(result);
} else {
res.send({});
}
});
});
当我再次调用该函数时,它给出了错误。 这是因为我看到我没有关闭连接。如果我尝试关闭连接,它也不起作用。 我尝试了 con.close()。 有什么办法可以让我摆脱这个
最佳答案
我认为使用池是最好的方法,我通过使用连接池并删除 .connect()
和 .end()
来修复此错误,使用 .release
相反,例如:
var pool = mysql.createPool({
connectionLimit : 10, // default = 10
host : 'localhost',
user : 'root',
password : '******',
database : 'test'
});
router.get('/users', function (req, res) {
pool.getConnection(function (err, connection) {
connection.query("SELECT * FROM table1", function (err, rows) {
connection.release();
if (err) throw err;
console.log(rows.length);
res.send(JSON.stringify(rows));
});
});
});
关于mysql - 错误: Cannot enqueue Handshake after already enqueuing a Handshake from nodejs application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915943/