Java JDBC连接状态 [英] Java JDBC connection status

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

问题描述

我使用以下方法(成功)连接到数据库:

I am (successfully) connecting to a database using the following:

java.sql.Connection connect = DriverManager.getConnection(
  "jdbc:mysql://localhost/some_database?user=some_user&password=some_password");

在一段时间后,我应该检查连接是否仍然打开和关闭?

我希望能有类似 connect.isConnected(); 的东西供我使用。

What should I be checking to see if the connection is still open and up after some time?
I was hoping for something like connect.isConnected(); available for me to use.

推荐答案

没什么。只需执行您的查询。如果连接已经死亡,您的JDBC驱动程序将重新连接(如果它支持它,并且您在连接字符串中启用它 - 大多数不支持它),否则您将获得异常。

Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.

如果您检查连接已启动,它可能会在您实际执行查询之前失败,因此您只需通过检查即可获得任何结果。

If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.

也就是说,许多连接池通过执行类似 SELECT 1 之类的操作来验证连接,然后再将连接移出。但这只不过是执行一个查询,所以你也可以执行你的业务查询。

That said, a lot of connection pools validate a connection by doing something like SELECT 1 before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.

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

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