DriverManager getConnection 的连接超时 [英] Connection timeout for DriverManager getConnection

查看:204
本文介绍了DriverManager getConnection 的连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用标准的 JDBC 方式连接到数据库

I am trying to connect to DB using the standard JDBC way

connection = DriverManager.getConnection(url, username, password);

连接超时是否有最大值,连接存活多长时间,我可以增加该值吗?我希望万一连接永远打开,这是个好主意.

Is there a maximum value of timeout on the connection, how long does a connection live, can I increase the value. I want in cases the connection to be open forever , is it a good idea.

推荐答案

该值通常由 DB 控制.您无法使用代码控制它.这取决于所使用的数据库服务器.通常在 30 分钟到 1 小时之间.

The value is usually DB-controlled. You have no control over it using code. It depends on the DB server used. It is usually around 30 minutes up to one hour.

另一方面,保持 Connection 永远打开是一个非常糟糕的主意.最佳实践是在最短中获取关闭ConnectionStatementResultSet避免资源泄漏和由泄漏和超时导致的潜在应用程序崩溃的可能范围.

On the other hand, keeping a Connection open forever is a very bad idea. Best practice is to acquire and close Connection, Statement and ResultSet in the shortest possible scope to avoid resource leaks and potential application crashes caused by the leaks and timeouts.

确实,连接数据库是一项昂贵的任务.如果您的应用程序应该运行相对较长的时间并且经常连接数据库,那么可以考虑使用连接池来提高连接性能.如果您的应用程序是 Web 应用程序,请查看应用程序服务器的文档,它通常提供具有 DataSource 风格的连接池工具.如果它是一个客户端应用程序,那么寻找已经证明其稳健性多年的第 3 方连接池库,例如 ApacheCommons DBCP(常用,在很多应用服务器中使用),C3P0(从 Hibernate 中得知)和 Proxool(如果您需要 XA 连接).

True, connecting the DB is an expensive task. If your application is supposed to run a relatively long time and to connect the DB fairly often, then consider using a connection pool to improve connecting performance. If your application is a webapplication, then take a look in the appserver's documentation, it usually provides a connection pooling facility in flavor of a DataSource. If it is a client application, then look for 3rd party connection pooling libraries which have proven their robustness with years, such as Apache Commons DBCP (commonly used, used in lot appservers), C3P0 (known from Hibernate) and Proxool (if you want XA connections).

请记住,在使用连接池时,您仍然需要编写正确的 JDBC 代码,即.在尽可能短的范围内获取关闭所有资源.连接池将依次担心实际关闭连接或只是将其释放回池以供进一步重用.

Keep in mind, when using a connection pool, you still have to write proper JDBC code, i.o.w. acquire and close all the resources in the shortest possible scope. The connection pool will on its turn worry about actually closing the connection or just releasing it back to pool for further reuse.

您可能会从这篇文章中获得更多见解 如何以正确的方式完成 JDBC 基础知识.

You may get some more insights out of this article how to do the JDBC basics the proper way.

希望这会有所帮助并祝您编码愉快.

Hope this helps and happy coding.

这篇关于DriverManager getConnection 的连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆