[英]node-mysql connection end or destroy not working
I don't know why mysql.end() or mysql.destroy() are not working as i expect.我不知道为什么 mysql.end() 或 mysql.destroy() 没有像我预期的那样工作。 This is my code.
这是我的代码。
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'db',
password: ''
});
connection.connect();
connection.query('SELECT * FROM ofertas ', function (err, rows, fields)
{
if (err) console.log(err);
else
{
console.log(rows);
}
});
connection.destroy(function (err)
{
if (err) throw err;
});
I execute this code and then i go to mysql command line and i type this:我执行此代码,然后从 go 到 mysql 命令行,然后输入:
show status like 'Conn%';
Before node code节点代码之前
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 3 |
+---------------+-------+
After node code节点代码后
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 4 |
+---------------+-------+
connection.state = 'disconnected' connection.state = '断开连接'
Thanks谢谢
You need to wait until the query is finished before you can destroy the connection. 您需要等到查询完成后才能销毁连接。 Try
尝试
connection.query('SELECT * FROM ofertas ', function (err, rows, fields)
{
if (err) console.log(err);
else
{
console.log(rows);
}
connection.destroy();
});
You can use the below code, for cleaner termination.您可以使用以下代码来更干净地终止。
connection.execute({
sqlText: 'select * from <TABLENAME>',
complete: function(err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
numRows =rows.length;
console.log('Number of rows produced: ' + numRows);
}
connection.destroy(function(err, conn) {
if (err) {
console.error('Unable to disconnect: ' + err.message);
} else {
console.log('Disconnected connection with id: ' + connection.getId());
}
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.