获取TypeError:无法在mysql node.js中调用null的方法'releaseConnection'

我正在使用mysql felix node.js模块。

我正在使用其连接池。

我有很多查询在我的服务器端(写在节点),是这样写的:

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

由于某种原因我不断收到这个错误(从这样写的各种函数):types错误:不能调用指向'connection.release()'行的null方法'releaseConnection'。 我真的不明白这里的问题是什么,因为我从API中了解了pool.getConnection的function,我应该可以完全访问连接。 也许这是连接超时所必须做的事情? 我相信不是这种情况,因为这个错误发生在我正在通过我的网站。

另一个问题:我必须处理连接将超时如果我使用池的选项? 如果答案是肯定的,我该怎么做?

谢谢。

我build议在尝试使用connection实例之前添加错误检查。 我已经更新了您的代码(请参阅我的评论内联):

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

此外,如果date实例来自不受信任的源,那么您的代码容易受到SQL注入攻击。 您可以考虑切换到mysql2并使用准备好的语句。