Java JDBC 连接状态

发布于 2024-12-09 23:09:29 字数 292 浏览 0 评论 0原文

我正在(成功)使用以下命令连接到数据库:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

傲世九天 2024-12-16 23:09:29

更新

哦,我刚刚看到自 1.6 以来有一个新方法可用:

java.sql.Connection.isValid(int timeoutSeconds)

如果连接尚未关闭且仍然有效,则返回 true。
驱动程序应提交连接查询或使用其他一些
积极验证连接仍然有效的机制
调用此方法。驱动程序提交的查询以进行验证
连接应在当前的上下文中执行
交易。


原始答案

您最好的机会是仅对一张表执行简单的查询,例如:

select 1 from SOME_TABLE;

UPDATE

Oh, I just saw there is a new method available since 1.6:

java.sql.Connection.isValid(int timeoutSeconds):

Returns true if the connection has not been closed and is still valid.
The driver shall submit a query on the connection or use some other
mechanism that positively verifies the connection is still valid when
this method is called. The query submitted by the driver to validate
the connection shall be executed in the context of the current
transaction.


ORIGINAL ANSWER

Your best chance is to just perform a simple query against one table, e.g.:

select 1 from SOME_TABLE;
嘿咻 2024-12-16 23:09:29

没有什么。只需执行您的查询即可。如果连接已断开,您的 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.

吻安 2024-12-16 23:09:29

使用Connection.isClosed()函数。

JavaDoc状态:

检索此Connection对象是否已关闭。一个
如果调用了 close 方法或者如果
发生了某些致命错误。该方法保证
仅当在 Connection.close 方法之后调用时才返回 true
已被调用。

Use Connection.isClosed() function.

The JavaDoc states:

Retrieves whether this Connection object has been closed. A
connection is closed if the method close has been called on it or if
certain fatal errors have occurred. This method is guaranteed to
return true only when it is called after the method Connection.close
has been called.

Hello爱情风 2024-12-16 23:09:29

您还可以使用

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}
红玫瑰 2024-12-16 23:09:29

如果您使用的是 MySQL,

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

我还没有测试过其他数据库。希望这有帮助。

If you are using MySQL

public static boolean isDbConnected() {
    final String CHECK_SQL_QUERY = "SELECT 1";
    boolean isConnected = false;
    try {
        final PreparedStatement statement = db.prepareStatement(CHECK_SQL_QUERY);
        isConnected = true;
    } catch (SQLException | NullPointerException e) {
        // handle SQL error here!
    }
    return isConnected;
}

I have not tested with other databases. Hope this is helpful.

俏︾媚 2024-12-16 23:09:29

无论供应商实现如何,低成本方法都是从进程内存或服务器内存中选择某些内容,例如数据库版本或当前数据库的名称。 IsClosed 的实现非常糟糕。

例子:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

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:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}
九公里浅绿 2024-12-16 23:09:29

如果您使用 JDBC 获取默认连接,这里有一个简单的解决方案

 private Connection getDefaultConnection() throws SQLException, ApiException {
    Connection connection = null;
    try {
         connection = dataSource.getConnection ();
    }catch (SQLServerException sqlException) {
        // DB_UNAVAILABLE EXCEPTION
    }
    return connection;
}

Here is a simple solution if you are using JDBC to get the default connection

 private Connection getDefaultConnection() throws SQLException, ApiException {
    Connection connection = null;
    try {
         connection = dataSource.getConnection ();
    }catch (SQLServerException sqlException) {
        // DB_UNAVAILABLE EXCEPTION
    }
    return connection;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文