简体   繁体   English

如何在MySQL数据库中保持活动的远程连接?

[英]How to keep Active remote Connections in MySQL Database?

I have a java application which has remote access in an online MySQL Database, and it works fine. 我有一个Java应用程序,该应用程序可以在线访问MySQL数据库,并且可以正常运行。

The only problem is that after a few minutes, the connection to the server was closed, is there anyway to keep the connection active? 唯一的问题是,几分钟后,与服务器的连接已关闭,是否仍然可以保持连接活动? So that I won't have to instantiate another connection just to perform the task. 这样我就不必为了执行任务而实例化另一个连接。

Any ideas and inputs would be much appreciated. 任何想法和投入将不胜感激。 Thanks in Advance. 提前致谢。

You need to auto reconnect, try editing your JDBC URL: 您需要自动重新连接,请尝试编辑JDBC URL:

jdbc:mysql://[host]:[port]/[database]? jdbc:mysql:// [主机]:[端口] / [数据库]? autoReconnect=true autoReconnect = true

See connector reference: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html 参见连接器参考: http : //dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

As other answers have pointed out you can use the autoReconnect option on the connection to solve the immediate problem. 正如其他答案所指出的那样,您可以在连接上使用autoReconnect选项来解决当前的问题。

However, if you are not using a database connection pool I would strongly suggest that you switch to one. 但是,如果您不使用数据库连接池,则强烈建议您切换到一个。

They have a number of advantages: 它们具有许多优点:

  • They check your connections for you - this deals with timeouts, network issues etc 他们为您检查连接-这涉及超时,网络问题等
  • They control the number of connections 它们控制连接数
  • You can simply 'close' the connection when your done with each bit of work and then 'reopen' a connection when needed. 完成每项工作后,您可以简单地“关闭”连接,然后在需要时“重新打开”连接。

If you manage connections yourself you will almost certainly end up writing some form of connection pool - and why reinvent the wheel. 如果您自己管理连接,则几乎可以肯定会写出某种形式的连接池-以及为什么要重新发明轮子。

By the time you have implemented connection checking so that they don't go stale, some sort of connection holder so that you don't need to re-open them each time, some sort of exception handling code you are well on your way to writing a lot of code that has already been written and thoroughly tested. 到您实施连接检查以使它们不会过时时,某种连接保持器使您不必每次都重新打开它们,某种异常处理代码很适合您编写许多已经编写并经过全面测试的代码。

I have used dbcp and boneCP and both are very easy to use and configure and will save you hours and hours of frustration dealing with JDBC connection issues. 我使用过dbcpboneCP ,它们都非常易于使用和配置,将为您节省数小时的处理JDBC连接问题的麻烦

jdbc:mysql://[host]:[port]/[database]?autoReconnect=true&user=root&password=passwordIchose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM