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

查看:23
本文介绍了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天全站免登陆