Error in MySQL Connection when accessing a remote server

折月煮酒 提交于 2019-12-04 16:18:04

Make sure you are not using a dead jdbc connection. Depending on how you are creating your jdbc connection they may be going idle. If you are using the same connection over and over, test the connection before you try to issue a query and get a new one if it has been closed by mysql.

UPDATE:

You create a new connection everywhere except getResult() which is where the stack trace identifies the error comes from. You can either create a new connection like you do everywhere else, or improve the encapsulation of getConnection(). In other words, change getConnection() to return the static Connection stored in your class, on condition it is not null and still valid. Otherwise create a new connection and return that.

This is a fairly common problem in MySQL, unfortunately occurring usually only after in production when application runs for some extended time unlike in the short development cycle.

MySQL closes connections without notifying its clients and the not much telling exception is what appears when you try to use a timed out connection. you could for example ping the connection with some trivial SQL statement periodically to avoid timeout.

It is a good practice to use a connection pool (to avoid problem with too many users accessing the DB at once), e.g. DBCP, in general. DBCP may be added to your application easily and you only set it as a quasi JDBC driver. There you can set things proper way.

I copied this DBCP config from one of my projects:

                 MaxActive=20,
                 MaxWait=60000,
                 TestWhileIdle=true,
                 TimeBetweenEvictionRunsMillis=300000,
                 MinEvictableIdleTimeMillis=300000,
                 TestOnBorrow=true,
                 ValidationQuery='SELECT 1'

Update: As a very simple solution, you could try catching the exception on access and open a new connection in that case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!