关闭连接MySQL Node.js

Uly*_*rez 3 node.js node-mysql

我正在使用ExpressJS和MySQL开发一个Node应用程序.我正在使用这个模块https://github.com/felixge/node-mysql/,我正在学习它的用途.我对如何正确关闭连接感到麻烦.

这就是我做的:

app.post('/example', function (req, res) {

    //BD
    var connection = mysql.createConnection({
        host: config.database.host,
        port: config.database.port,
        user: config.database.user,
        password: config.database.password,
        database: config.database.database
    });

    var sql = '';

    if (varExample != null) {

         sql = 'Random query';

         connection.query(sql, function (err, results) {

             //Get results

             connection.end();
         }); 
    }
});
Run Code Online (Sandbox Code Playgroud)

有时我必须多次调用此方法才能在数据库中插入数据.那一刻我得到一个错误'太多连接'.

在这些情况下关闭连接的方法是什么?

Dev*_*ien 7

你不应该做的是每次收到请求时打开一个连接.每次连接都很慢,第二,驱动程序通常会为您打开一个连接池,所以不应该是一个问题.没有必要关闭与mysql的连接.

基本上你必须这样做

//BD
var connection = mysql.createConnection({
    host: config.database.host,
    port: config.database.port,
    user: config.database.user,
    password: config.database.password,
    database: config.database.database
});
app.post('/example', function (req, res) {
    var sql = '';

    if (varExample != null) {

         sql = 'Random query';

         connection.query(sql, function (err, results) {

            //Get results
         });  
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:添加池选项拥有一个连接池基本上是我们大多数人想要的服务器,它必须做很多查询.它只是稍微改变了你创建连接的方式.

var connection  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret'
});
Run Code Online (Sandbox Code Playgroud)


tie*_*er1 5

我意识到已经有了一个可以接受的答案,但是您真正应该做的是创建一个数据库池,而其他答案实际上并没有给出示例。与使用库创建普通数据库连接相比,您必须对此进行一些设置。

-edit您不必担心关闭连接。

    var mysql = require('mysql');
    var pool  = mysql.createPool({
      connectionLimit : 10,
      host            : 'example.org',
      user            : 'bob',
      password        : 'secret'
    });

    pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      if (err) throw err;

      console.log('The solution is: ', rows[0].solution);
    });

exports.Pool = pool;
Run Code Online (Sandbox Code Playgroud)