Java JDBC 连接状态
我正在(成功)使用以下命令连接到数据库:
java.sql.Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost/some_database?user=some_user&password=some_password");
我应该检查什么来查看连接在一段时间后是否仍然打开并启动?
我希望有像 connect.isConnected();
这样的东西可供我使用。
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");
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
更新
哦,我刚刚看到自 1.6 以来有一个新方法可用:
java.sql.Connection.isValid(int timeoutSeconds)
:原始答案
您最好的机会是仅对一张表执行简单的查询,例如:
UPDATE
Oh, I just saw there is a new method available since 1.6:
java.sql.Connection.isValid(int timeoutSeconds)
:ORIGINAL ANSWER
Your best chance is to just perform a simple query against one table, e.g.:
没有什么。只需执行您的查询即可。如果连接已断开,您的 JDBC 驱动程序将重新连接(如果它支持它,并且您在连接字符串中启用了它 - 大多数不支持它),否则您将收到异常。
如果您检查连接是否已启动,则在实际执行查询之前它可能会失败,因此您通过检查绝对不会获得任何好处。
也就是说,许多连接池在分发连接之前会通过执行诸如 SELECT 1 之类的操作来验证连接。但这只不过是执行一个查询,所以您也可以执行您的业务查询。
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.
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.使用Connection.isClosed()函数。
JavaDoc状态:
Use
Connection.isClosed()
function.The JavaDoc states:
您还可以使用
You also can use
如果您使用的是 MySQL,
我还没有测试过其他数据库。希望这有帮助。
If you are using MySQL
I have not tested with other databases. Hope this is helpful.
无论供应商实现如何,低成本方法都是从进程内存或服务器内存中选择某些内容,例如数据库版本或当前数据库的名称。 IsClosed 的实现非常糟糕。
例子:
The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.
Example:
如果您使用 JDBC 获取默认连接,这里有一个简单的解决方案
Here is a simple solution if you are using JDBC to get the default connection