简体   繁体   中英

getting TypeError: Cannot call method 'releaseConnection' of null in mysql node.js

i am using mysql felix node.js module.

i am using its pool connection.

i have many queries in my server side (written in node) that are written like this:

  this.courtsAmount = function(date, callback){
  pool.getConnection(function(err, connection) {
    connection.query('SELECT MAX(id) AS result from courts where date="' + date + '"', function(err, rows, fields){
        connection.release();
        if (err) throw err;           
        if (rows[0].result)
          callback(rows[0].result);
        else
          callback(0);
        });
  });
    };

for some reason i keep getting this error (from all sorts of functions that are written like this): Type Error: Cannot call method 'releaseConnection' of null which is pointing to the 'connection.release()' line. i really don't understand what is the problem here, as i understand from the API inside the function of pool.getConnection i am supposed to have full access to the connection. maybe it is an issue of something to have to do with timeout of the connection? i believe it is not the case because this error happens while i am actually going through my site.

another question: do i have to deal with the option that connections will timeout if i use the pool? and if the answer is yes, how should i do it?

thanks.

I'd recommend adding error checking before attempting to use the connection instance. I've updated your code (see my comments inline):

this.courtsAmount = function(date, callback) {
  pool.getConnection(function(err, connection) {
    if (err) throw err; // <-- 'connection' might be null, so add an error check here
    connection.query('SELECT MAX(id) AS result from courts where date="' + date + '"', function(err, rows, fields) {
      if (err) throw err; // <-- moved this line up to check for an error first
      connection.release();  // <-- moved this line down so error checking happens first
      if (rows[0].result)
        callback(rows[0].result);
      else
        callback(0);
    });
  });
};

Also, if the date instance is coming from an untrusted source, then your code is vulnerable to SQL injection. You might consider switching to mysql2 and using a prepared statement.

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