node-mysql连接结束或销毁无法正常工作

时间:2015-05-11 08:01:12

标签: mysql node.js node-mysql

我不知道为什么mysql.end()或mysql.destroy()不能正常工作。这是我的代码。

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;
});

我执行此代码,然后我转到mysql命令行,我输入:

show status like 'Conn%';

节点代码之前

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections   | 3     |
+---------------+-------+

节点代码

之后
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections   | 4     |
+---------------+-------+

connection.state ='disconnected'

由于

1 个答案:

答案 0 :(得分:1)

您需要等到查询完成才能销毁连接。尝试

connection.query('SELECT * FROM ofertas ', function (err, rows, fields)
{
    if (err) console.log(err);
    else
    {
        console.log(rows);
    }
    connection.destroy();
});