MySql连接错误使用Node.js

连接丢失:服务器closures连接

使用Node.js使用node_modules mysql 我安装了npm的nodemon模块来连续监视我的node.js应用程序,并在服务器崩溃时重启服务器,当服务器崩溃时,应用程序本身不会重新启动。

示例图像上传下面与错误描述。

只有在任何模块或文件发生任何更改的情况下,Nodemon才会重新启动应用程序!

这可能与wait_timeout服务器variables有关。 当数秒内没有数据通过连接时,服务器将断开连接。 你可以提高设置,但是你可能会面临更多闲置连接的风险,最终无论如何你会再次触发暂停。

最好的解决scheme是在发生这种情况时重新build立客户端连接,而这似乎并不支持开箱即用,但是您可以自己实现: https://www.exratione。 COM / 2013/01 /的NodeJS-连接意志端近距离和-否则-吹塑-上/

另一个解决scheme可能是周期性地(在超时之前)做一个简单的查询,如SELECT 1来保持连接的连接。

search大量网站和实施代码后,我已经成功地解决了上述错误。 为此,我使用了mysqlpool。 代码如下所示。

首先你声明这样的连接:

 var mysql = require('mysql'); var mysqlPool = mysql.createPool({ host : "localhost", user : "username", password: "password", database :"databasename", port:3306 }); 

现在你的连接configuration已经成功创build和使用像这样:

 var strQuery = "SELECT * FROM userdetails"; //here store sql query in strQuery variable. mysqlPool.getConnection(function(err, connection) { if(err) throw err; connection.query(strQuery, function(err, rows) { if(err) { // if error occures goes here. connection.end(); // if error occured closed the connection console.error(err); return; } //If no error here you get your query output. console.log(rows[0].User_name); //retrieved username & print into console log or you can also retrived any rows like this. connection.end();// After performing the operation then closed the connection. }); });