有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jdbc如何在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这样的错误消息。它没有在连接字符串中给出主机名。我想显示主机名(或连接字符串),以便对其进行诊断


共 (1) 个答案

  1. # 1 楼答案

    这是一条来自甲骨文的愚蠢错误信息。网络适配器不建立连接。是的。正如你所说,它会抑制所有重要信息

    但是,通过追踪原始异常中的detail链,进一步查看调用堆栈。某处应该有一个ConnectException带有你想要的信息