[英]getting TypeError: Cannot call method 'releaseConnection' of null in mysql node.js
i am using mysql felix node.js module. 我正在使用mysql felix node.js模块。
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. 由于某种原因,我不断收到此错误(从各种类似函数编写的错误中):类型错误:无法调用指向“ connection.release()”行的null的方法“ releaseConnection”。 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. 我真的不明白这里是什么问题,因为我从pool.getConnection函数内部的API中了解到,我应该可以完全访问该连接。 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. 我建议在尝试使用connection
实例之前添加错误检查。 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. 此外,如果date
实例来自不受信任的来源,则您的代码容易受到SQL注入的攻击。 You might consider switching to mysql2 and using a prepared statement. 您可能会考虑切换到mysql2并使用准备好的语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.