一尘不染

如何获取连接字符串而无需在Java中打开连接?

java

用Java可以做到吗?连接字符串中的主机无法解析,因此在能够在连接上调用getMetaData之前,我在DataSource的getConnection()中获取了SQLException。

这是我的代码:

DataSource ds = null;
Connection connection = null;
DataSourceProbeRequest request = null;

try {
  request = (DataSourceProbeRequest) probeRequest;

  ds = request.getDataSource();

  connection = ds.getConnection();
  final boolean validConnection = connection != null && connection.isValid(5000);
  if (validConnection) {
    LOGGER.info("Connection is ok: " + request.getTargetId());
    return new ProbeResult(request.getTargetId(), buildDatasourceMsg(connection, true));
  } else {
    return new ProbeResult(request.getTargetId(), new Exception(buildDatasourceMsg(connection, false)));
  }
} catch (Exception exp) {
  return new ProbeResult(request.getTargetId(), exp);
} finally {
  if (connection != null) {
    try {
      connection.close();
    } catch (SQLException e) {
      LOGGER.warn("Failed to close database connection", e);
    }
  }
}

由于主机不可访问,connection = ds.getConnection();将引发异常并导致new ProbeResult(request.getTargetId(), exp)返回。但是,该异常仅具有诸如之类的错误消息IO Error: The Network Adapter could not establish the connection。它没有在连接字符串中给出主机名。我想显示主机名(或连接字符串)以便可以对其进行诊断


阅读 185

收藏
2020-12-03

共1个答案

一尘不染

这是来自Oracle的愚蠢错误消息。网络适​​配器不建立连接。TCP。而且,正如您所说,它隐藏了所有重要信息。

但是,通过追踪detail原始异常中的链,可以进一步了解调用堆栈。某个地方应该ConnectException带有您想要的消息。

2020-12-03