简体   繁体   中英

Keeping mysql connection on Express

so I'm quite new to nodejs and express. There's a service I'm trying to create, and I noticed that I can't simply keep the mysql connection by stating connection.connect() again. So I came up with this way of continuing the connection, but I wasn't sure if this is the right way to keep the connection. Can any of you take a look at the commented portion in the middle of the code?

app.get('/keyboard', function(req, res){
    connection.connect();
    connection.query("SELECT `hour` from timetable WHERE `reserved` = '0'", function(err, rows, fields){

            if(err) throw err;
            var buttons = [];
            for(var i = 0; i < rows.length; i++){

                    buttons.push(rows[i].hour);
            }

            console.log("available time: " + buttons);

            var return_data = {

                    "type"    : "buttons",
                    "buttons" : buttons
            };
            //console.log(return_data);
            res.send(return_data);

    });

    connection.end(); // connection ends here
    //connection.connect() doesn't create a new connection.
    connection = mysql.createConnection({ // another connection like this?
            host     : 'localhost',
            user     : 'user',
            password : 'pw',
            database : 'db'
    });
});

In this scenario you should think over using the pool functionality provided by the mysql library. The pool will take over the task to manage the connections.

var mysql = require('mysql');
var pool = mysql.createPool({ // another connection like this?
  host: 'localhost',
  user: 'user',
  password: 'pw',
  database: 'db',
  connectionLimit : 10 // its depends on requirement  
});


app.get('/keyboard', function(req, res) {
  pool.query("SELECT `hour` from timetable WHERE `reserved` = '0'", function(err, rows, fields) {

    if (err) throw err;

    var buttons = [];
    for (var i = 0; i < rows.length; i++) {
      buttons.push(rows[i].hour);
    }

    console.log("available time: " + buttons);

    var return_data = {

      "type": "buttons",
      "buttons": buttons
    };
    //console.log(return_data);
    res.send(return_data);
  });
})

You can use a pool like a regular connection, the difference is that the mysql module will request a new connection out of its pool on each call on the pool object, and release that connection after the query is finished.

This is important if you need to use Transactions if you need to do another kind multiple queries the use per connection states. Eg something like this might fail, or have unexpected behavior:

pool.query("START TRANSACTION")
pool.query("SELECT ...") // some query
pool.query("COMMIT")

For such a case you would need to write it that way, but there you need to release the connection back to the pool using connection.release();

pool.getConnection(function(err, connection) {
  connection.query("START TRANSACTION")
  pool.query("SELECT ...") // some query
  connection.query("COMMIT", function() {
    connection.release();
  })
});

You can defined a connection limit for the pool using the connectionLimit , this can become handy if you want to control/limit the load on the mysql server.

(See Pooling connections , for more details)

You can create a connection using polling method using node-mysql-pool npm module.

var MySQLPool = require("mysql-pool").MySQLPool;
var pool = new MySQLPool({
  poolSize: 4,// it can be number of connections
  user:     'root',
  password: 'root',
  database: 'test'
});

pool.query("SELECT 'Hello, World!' AS hello", function(err, rows, fields) {
  if(err) throw err;
  console.log(rows[0].hello);
});

for(var i = 0; i < 10; ++i) {
  pool.query("SELECT SLEEP(2), ? AS i", [i], function(err, rows, fields) {
    if(err) throw err;
    console.log("Slept: " + rows[0].i);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM